Java Code Examples for com.google.common.base.Suppliers#ofInstance()

The following examples show how to use com.google.common.base.Suppliers#ofInstance() . 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: SchedulerTest.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public void testEarliestStartLaterWinsToDependency() {
  getTaskManager().getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().setEnabled(false);

  // task0 starts on Mo.
  // task1 start date on Tu, earliest start is set to We
  // Despite the dependency task0->task1 earliest start wins and we move task1 forward
  Task[] tasks = new Task[] {createTask(TestSetupHelper.newMonday()), createTask(TestSetupHelper.newTuesday())};
  tasks[1].setThirdDateConstraint(TaskImpl.EARLIESTBEGIN);
  tasks[1].setThirdDate(TestSetupHelper.newWendesday());
  TaskDependency[] deps = new TaskDependency[] {createDependency(tasks[1], tasks[0])};
  DependencyGraph graph = createGraph(tasks, deps);

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

  assertEquals(TestSetupHelper.newWendesday(), tasks[1].getStart());
}
 
Example 2
Source File: SchedulerTest.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public void testRubberFS_StrongFF() throws Exception {
  // task0->task1 FS rubber, task2->task1 FF strong
  // task0 starts on Mo, task1 initially on Tu, task2 on We
  Task[] tasks = new Task[] {createTask(TestSetupHelper.newMonday()), createTask(TestSetupHelper.newTuesday()), createTask(TestSetupHelper.newWendesday())};
  TaskDependency dep10 = getTaskManager().getDependencyCollection().createDependency(tasks[1], tasks[0], new FinishStartConstraintImpl(), TaskDependency.Hardness.RUBBER);
  TaskDependency dep12 = getTaskManager().getDependencyCollection().createDependency(tasks[1], tasks[2], new FinishFinishConstraintImpl(), TaskDependency.Hardness.STRONG);

  DependencyGraph graph = createGraph(tasks, new TaskDependency[] {dep10, dep12});
  SchedulerImpl scheduler = new SchedulerImpl(graph, Suppliers.ofInstance(getTaskManager().getTaskHierarchy()));
  scheduler.run();

  // after scheduler run task1 shoud start on We because of strong FF dep
  assertEquals(TestSetupHelper.newMonday(), tasks[0].getStart());
  assertEquals(TestSetupHelper.newWendesday(), tasks[1].getStart());
  assertEquals(TestSetupHelper.newWendesday(), tasks[2].getStart());

  // now shifting task2 to Tu
  tasks[2].shift(getTaskManager().createLength(-1));
  scheduler.run();

  // task1 should follow task2
  assertEquals(TestSetupHelper.newTuesday(), tasks[1].getStart());
  assertEquals(TestSetupHelper.newTuesday(), tasks[2].getStart());
  assertEquals(TestSetupHelper.newWendesday(), tasks[1].getEnd());
}
 
Example 3
Source File: SchedulerTest.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public void testEarliestStartLaterThanStartDate() {
  getTaskManager().getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().setEnabled(false);

  // start date on Mo, but earliest start is set to We.
  // task should be shifted forward
  Task[] tasks = new Task[] {createTask(TestSetupHelper.newMonday())};
  tasks[0].setThirdDateConstraint(TaskImpl.EARLIESTBEGIN);
  tasks[0].setThirdDate(TestSetupHelper.newWendesday());
  TaskDependency[] deps = new TaskDependency[0];
  DependencyGraph graph = createGraph(tasks, deps);

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

  assertEquals(TestSetupHelper.newWendesday(), tasks[0].getStart());
}
 
Example 4
Source File: EndpointsTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Test
public void testSupplierFactory() throws Exception {
  final DnsResolver resolver = mock(DnsResolver.class);
  when(resolver.resolve("example.com")).thenReturn(IPS_1);
  when(resolver.resolve("example.net")).thenReturn(IPS_2);
  final Supplier<List<URI>> uriSupplier = Suppliers.ofInstance(uris);
  final Supplier<List<Endpoint>> endpointSupplier = Endpoints.of(uriSupplier, resolver);
  final List<Endpoint> endpoints = endpointSupplier.get();

  assertThat(endpoints.size(), equalTo(4));
  assertThat(endpoints.get(0).getUri(), equalTo(uri1));
  assertThat(endpoints.get(0).getIp(), equalTo(IP_A));
  assertThat(endpoints.get(1).getUri(), equalTo(uri1));
  assertThat(endpoints.get(1).getIp(), equalTo(IP_B));
  assertThat(endpoints.get(2).getUri(), equalTo(uri2));
  assertThat(endpoints.get(2).getIp(), equalTo(IP_C));
  assertThat(endpoints.get(3).getUri(), equalTo(uri2));
  assertThat(endpoints.get(3).getIp(), equalTo(IP_D));
}
 
Example 5
Source File: BundleUpgradeParserTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void checkParseRemovals(Bundle bundle) {
    Supplier<Iterable<RegisteredType>> typeSupplier = Suppliers.ofInstance(ImmutableList.of());
    
    CatalogUpgrades upgrades = BundleUpgradeParser.parseBundleManifestForCatalogUpgrades(bundle, typeSupplier);
    assertFalse(upgrades.isEmpty());
    assertTrue(upgrades.isBundleRemoved(new VersionedName("org.example.brooklyn.mybundle", "0.1.0")));
    assertFalse(upgrades.isBundleRemoved(new VersionedName("org.example.brooklyn.mybundle", "1.0.0")));
    
    assertTrue(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "0.1.0")));
    assertTrue(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "0.1.0-SNAPSHOT")));
    assertTrue(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "0.0.0-SNAPSHOT")));
    assertFalse(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "1.0.0")));
    assertTrue(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "1.0.0.SNAPSHOT")));
    assertFalse(upgrades.isLegacyItemRemoved(newMockCatalogItem("foo", "1.0.0.GA")));
    
    assertTrue(upgrades.isLegacyItemRemoved(newMockCatalogItem("bar", "0.1.0")));
    assertFalse(upgrades.isLegacyItemRemoved(newMockCatalogItem("bar", "1.0.0")));
    assertFalse(upgrades.isLegacyItemRemoved(newMockCatalogItem("bar", "1.0.0.SNAPSHOT")));
    
    assertFalse(upgrades.isLegacyItemRemoved(newMockCatalogItem("different", "0.1.0")));
}
 
Example 6
Source File: DedupQueueTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@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(), Matchers.eq(true));
    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(), Matchers.eq(true));
    verifyNoMoreInteractions(readerDao);
}
 
Example 7
Source File: SslServerInitializerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ChannelHandler getServerHandler(
    boolean requireClientCert,
    boolean validateClientCert,
    PrivateKey privateKey,
    X509Certificate... certificates) {
  return new SslServerInitializer<LocalChannel>(
      requireClientCert,
      validateClientCert,
      sslProvider,
      Suppliers.ofInstance(privateKey),
      Suppliers.ofInstance(ImmutableList.copyOf(certificates)));
}
 
Example 8
Source File: WeaverTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldStillCallOnAfterOfHigherPriorityPointcut() throws Exception {
    // given

    // SomeAspectThreadLocals is passed as bridgeable so that the static thread locals will be
    // accessible for test verification
    IsolatedWeavingClassLoader isolatedWeavingClassLoader = new IsolatedWeavingClassLoader(
            Misc.class, SomeAspectThreadLocals.class, IntegerThreadLocal.class);
    List<Advice> advisors = Lists.newArrayList();
    advisors.add(newAdvice(BasicAdvice.class));
    advisors.add(newAdvice(BindThrowableAdvice.class));
    advisors.add(newAdvice(ThrowInOnBeforeAdvice.class));
    advisors.add(newAdvice(BasicHighOrderAdvice.class));
    Supplier<List<Advice>> advisorsSupplier =
            Suppliers.<List<Advice>>ofInstance(ImmutableList.copyOf(advisors));
    AnalyzedWorld analyzedWorld = new AnalyzedWorld(advisorsSupplier,
            ImmutableList.<ShimType>of(), ImmutableList.<MixinType>of(), null);
    TransactionRegistry transactionRegistry = mock(TransactionRegistry.class);
    when(transactionRegistry.getCurrentThreadContextHolder())
            .thenReturn(new ThreadContextThreadLocal().getHolder());
    Weaver weaver = new Weaver(advisorsSupplier, ImmutableList.<ShimType>of(),
            ImmutableList.<MixinType>of(), analyzedWorld, transactionRegistry,
            Ticker.systemTicker(), new TimerNameCache(), mock(ConfigService.class));
    isolatedWeavingClassLoader.setWeaver(weaver);
    Misc test = isolatedWeavingClassLoader.newInstance(BasicMisc.class, Misc.class);
    // when
    RuntimeException exception = null;
    try {
        test.execute1();
    } catch (RuntimeException e) {
        exception = e;
    }
    // then
    assertThat(exception.getMessage()).isEqualTo("Abxy");
    assertThat(SomeAspectThreadLocals.onBeforeCount.get()).isEqualTo(1);
    assertThat(SomeAspectThreadLocals.onReturnCount.get()).isEqualTo(0);
    assertThat(SomeAspectThreadLocals.onThrowCount.get()).isEqualTo(2);
    assertThat(SomeAspectThreadLocals.onAfterCount.get()).isEqualTo(1);
    assertThat(SomeAspectThreadLocals.throwable.get().getMessage()).isEqualTo("Abxy");
}
 
Example 9
Source File: BundleUpgradeParserTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testForgetQuotesGivesNiceError() throws Exception {
    Bundle bundle = newMockBundle(ImmutableMap.of(
            BundleUpgradeParser.MANIFEST_HEADER_FORCE_REMOVE_LEGACY_ITEMS, "foo:[0,1.0.0),bar:[0,1.0.0)"));
    Supplier<Iterable<RegisteredType>> typeSupplier = Suppliers.ofInstance(ImmutableList.of());
    
    try {
        BundleUpgradeParser.parseBundleManifestForCatalogUpgrades(bundle, typeSupplier);
        Asserts.shouldHaveFailedPreviously();
    } catch (Exception e) {
        Asserts.expectedFailureContainsIgnoreCase(e, "quote");
    }
}
 
Example 10
Source File: DefaultDatabusTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void testSubscribeWithBadSubscriptionTTLCreation() {
    Supplier<Condition> ignoreReEtl = Suppliers.ofInstance(
            Conditions.not(Conditions.mapBuilder().matches(UpdateRef.TAGS_NAME, Conditions.containsAny("re-etl")).build()));
    DefaultDatabus testDatabus = new DefaultDatabus(
            mock(LifeCycleRegistry.class), mock(DatabusEventWriterRegistry.class), mock(DataProvider.class), mock(SubscriptionDAO.class),
            mock(DatabusEventStore.class), mock(SubscriptionEvaluator.class), mock(JobService.class),
            mock(JobHandlerRegistry.class), mock(DatabusAuthorizer.class), "replication", ignoreReEtl, mock(ExecutorService.class),
            1, key -> 0, mock(MetricRegistry.class), Clock.systemUTC());
    Condition condition = Conditions.intrinsic(Intrinsic.TABLE, "test");
    Duration subscriptionTtl = Duration.ofDays(365 * 10).plus(Duration.ofDays(1));
    Duration eventTtl = Duration.ofDays(2);

    testDatabus.subscribe("id", "test-subscription", condition,subscriptionTtl, eventTtl);
}
 
Example 11
Source File: FontChooserTest.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
public void testNoFontStyle() {
  Properties p = new Properties();
  FontChooser chooser = new FontChooser(p, null, Suppliers.ofInstance(myBaseFont));
  Font font = chooser.getFont("nosuchstyle");
  assertEquals(10, font.getSize());
  assertEquals("Dialog", font.getFamily());
}
 
Example 12
Source File: RowGroupResultSetIterator.java    From emodb with Apache License 2.0 4 votes vote down vote up
public RowGroupResultSetIterator(ResultSet resultSet, int prefetchLimit) {
    this(Suppliers.ofInstance(resultSet), prefetchLimit);
}
 
Example 13
Source File: Target.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
public Supplier<List<URI>> getEndpointSupplier() {
  final List<URI> endpoints = ImmutableList.of(endpoint);
  return Suppliers.ofInstance(endpoints);
}
 
Example 14
Source File: GoogleHadoopFileSystemBase.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
private void setGcsFs(GoogleCloudStorageFileSystem gcsFs) {
  this.gcsFsSupplier = Suppliers.ofInstance(gcsFs);
  this.gcsFsInitialized = true;
}
 
Example 15
Source File: WriteFileStep.java    From buck with Apache License 2.0 4 votes vote down vote up
public WriteFileStep(
    ProjectFilesystem filesystem, String content, Path outputPath, boolean executable) {
  this(filesystem, Suppliers.ofInstance(content), outputPath, executable);
}
 
Example 16
Source File: EthGetBalance.java    From besu with Apache License 2.0 4 votes vote down vote up
public EthGetBalance(final BlockchainQueries blockchain) {
  this(Suppliers.ofInstance(blockchain));
}
 
Example 17
Source File: SshPutTaskFactory.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SshPutTaskFactory contents(Reader reader) {
    markDirty();
    this.contents = Suppliers.ofInstance(new ReaderInputStream(reader));  
    return self();
}
 
Example 18
Source File: DefaultDatabusTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Test
public void testDrainQueueForItemsInMultiplePeeks() {
    Supplier<Condition> ignoreReEtl = Suppliers.ofInstance(
            Conditions.not(Conditions.mapBuilder().matches(UpdateRef.TAGS_NAME, Conditions.containsAny("re-etl")).build()));
    final List<String> actualIds = Lists.newArrayList();
    DedupEventStore dedupEventStore = mock(DedupEventStore.class);
    DatabusEventStore eventStore = new DatabusEventStore(mock(EventStore.class), dedupEventStore, Suppliers.ofInstance(true)) {
        private int iteration = 0;

        @Override
        public boolean peek(String subscription, EventSink sink) {
            // The single peek will return one item followed with a "more":true value. Finally, a "more":false value when done.
            if (iteration++ < 3) {
                String id = "a" + iteration;
                actualIds.add(id);
                assertTrue(sink.remaining() > 0);
                EventSink.Status status = sink.accept(newEvent(id, "table", "key", TimeUUIDs.newUUID()));
                assertEquals(status, EventSink.Status.ACCEPTED_CONTINUE);
                return true;
            }
            return false;
        }
    };
    Map<String, Object> content = entity("table", "key", ImmutableMap.of("rating", "5"));
    // Create a custom annotated content which returns all changes as redundant
    DataProvider.AnnotatedContent annotatedContent = mock(DataProvider.AnnotatedContent.class);
    when(annotatedContent.getContent()).thenReturn(content);
    when(annotatedContent.isChangeDeltaRedundant(any(UUID.class))).thenReturn(true);

    DefaultDatabus testDatabus = new DefaultDatabus(
            mock(LifeCycleRegistry.class), mock(DatabusEventWriterRegistry.class), new TestDataProvider().add(annotatedContent), mock(SubscriptionDAO.class),
            eventStore, mock(SubscriptionEvaluator.class), mock(JobService.class),
            mock(JobHandlerRegistry.class), mock(DatabusAuthorizer.class), "systemOwnerId", ignoreReEtl, MoreExecutors.sameThreadExecutor(),
            1, key -> 0, new MetricRegistry(), Clock.systemUTC());

    // Call the drainQueue method.
    testDatabus.drainQueueAsync("test-subscription");

    assertEquals(testDatabus.getDrainedSubscriptionsMap().size(), 0);

    for (String actualId : actualIds) {
        verify(dedupEventStore).delete("test-subscription", ImmutableList.of(actualId), true);
    }
    verifyNoMoreInteractions(dedupEventStore);

    // the entry should be removed from map.
    assertEquals(testDatabus.getDrainedSubscriptionsMap().size(), 0);
}
 
Example 19
Source File: CertificateSupplierModule.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Singleton
@Provides
@P12File
static Supplier<PrivateKey> provideP12PrivateKeySupplier() {
  return Suppliers.ofInstance(null);
}
 
Example 20
Source File: IllegalStateExceptionSupplier.java    From brooklyn-server with Apache License 2.0 votes vote down vote up
public IllegalStateExceptionSupplier(String message, Throwable cause) { this(Suppliers.ofInstance(message), cause); }