java.util.function.Supplier Java Examples

The following examples show how to use java.util.function.Supplier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityRealmService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SecurityRealmService(final Consumer<SecurityRealm> securityRealmConsumer,
                     final Supplier<SubjectSupplementalService> subjectSupplementalSupplier,
                     final Supplier<CallbackHandlerFactory> secretCallbackFactorySupplier,
                     final Supplier<KeytabIdentityFactoryService> keytabFactorySupplier,
                     final Supplier<SSLContext> sslContextSupplier,
                     final Supplier<String> tmpDirPathSupplier,
                     final Set<Supplier<CallbackHandlerService>> callbackHandlerServices,
                     final String name, final boolean mapGroupsToRoles) {
    this.securityRealmConsumer = securityRealmConsumer;
    this.subjectSupplementalSupplier = subjectSupplementalSupplier;
    this.secretCallbackFactorySupplier = secretCallbackFactorySupplier;
    this.keytabFactorySupplier = keytabFactorySupplier;
    this.sslContextSupplier = sslContextSupplier;
    this.tmpDirPathSupplier = tmpDirPathSupplier;
    this.callbackHandlerServices = callbackHandlerServices;
    this.name = name;
    this.mapGroupsToRoles = mapGroupsToRoles;
}
 
Example #2
Source File: AppUtils.java    From java-ml-projects with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Perform an async call
 * 
 * @param action
 * @param success
 * @param error
 */
public static <T extends Object> void doAsyncWork(Supplier<T> action, Consumer<T> success,
		Consumer<Throwable> error) {
	Task<T> tarefaCargaPg = new Task<T>() {
		@Override
		protected T call() throws Exception {
			return action.get();
		}

		@Override
		protected void succeeded() {
			success.accept(getValue());
		}

		@Override
		protected void failed() {
			error.accept(getException());
		}
	};
	Thread t = new Thread(tarefaCargaPg);
	t.setDaemon(true);
	t.start();
}
 
Example #3
Source File: Seq.java    From mockneat with Apache License 2.0 6 votes vote down vote up
@Override
public Supplier<T> supplier() {
    return () -> {
        if (iterator.hasNext())
            return (T) iterator.next();
        else
            if (cycle) {
                this.iterator = iterable.iterator();
                return (T) iterator.next();
            }
            else {
                if (after == null) {
                    return null;
                }
                return (T) after.get();
            }
    };
}
 
Example #4
Source File: SpliteratorTraversingAndSplittingTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static <T, S extends Spliterator<T>> void testSplitOnce(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    S spliterator = supplier.get();
    long sizeIfKnown = spliterator.getExactSizeIfKnown();
    boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);

    ArrayList<T> fromSplit = new ArrayList<>();
    Spliterator<T> s1 = supplier.get();
    Spliterator<T> s2 = s1.trySplit();
    long s1Size = s1.getExactSizeIfKnown();
    long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
    Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
    if (s2 != null)
        s2.forEachRemaining(addToFromSplit);
    s1.forEachRemaining(addToFromSplit);

    if (sizeIfKnown >= 0) {
        assertEquals(sizeIfKnown, fromSplit.size());
        if (s1Size >= 0 && s2Size >= 0)
            assertEquals(sizeIfKnown, s1Size + s2Size);
    }
    assertContents(fromSplit, exp, isOrdered);
}
 
Example #5
Source File: SqlBacking.java    From ClaimChunk with MIT License 6 votes vote down vote up
static boolean getTableDoesntExist(ClaimChunk claimChunk,
                                   Supplier<Connection> connection,
                                   String databaseName,
                                   String tableName) throws SQLException {
    String sql = "SELECT count(*) FROM information_schema.TABLES WHERE (`TABLE_SCHEMA` = ?) AND (`TABLE_NAME` = ?)";
    try (PreparedStatement statement = prep(claimChunk, connection, sql)) {
        statement.setString(1, databaseName);
        statement.setString(2, tableName);
        try (ResultSet results = statement.executeQuery()) {
            if (results.next()) {
                return results.getInt(1) <= 0;
            }
        }
    }
    return true;
}
 
Example #6
Source File: TestLoggerFinder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static LogEvent of(long sequenceNumber,
        boolean isLoggable, String name,
        Logger.Level level, ResourceBundle bundle,
        String key, Supplier<String> supplier,
        Throwable thrown, Object... params) {
    LogEvent evt = new LogEvent(sequenceNumber);
    evt.loggerName = name;
    evt.level = level;
    evt.args = params;
    evt.bundle = bundle;
    evt.thrown = thrown;
    evt.supplier = supplier;
    evt.msg = key;
    evt.isLoggable = isLoggable;
    return evt;
}
 
Example #7
Source File: SeleniumTestBase.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
@Parameters(name = "Selenium JS test: {1} (quirks-mode={2})")
public static Iterable<Object[]> sauceLabBrowsersToTest() {
    final Collection<Object[]> browserList;
    if (!System.getenv().containsKey(DRIVER_ENV_VAR)) {
        browserList = Collections.emptyList();
    } else if (SAUCE_DRIVER.equals(System.getenv().get(DRIVER_ENV_VAR))) {
        browserList = SAUCE_BROWSER_LIST;
        logger.info("Selenium test running on SauceLabs with these browsers:\n{}",
                    browserNameList(SAUCE_BROWSER_LIST));
    } else if (BS_DRIVER.equals(System.getenv().get(DRIVER_ENV_VAR))) {
        browserList = BS_BROWSER_LIST;
        logger.info("Selenium test running on BrowserStack with these browsers:\n{}",
                    browserNameList(BS_BROWSER_LIST));
    } else {
        // Parameters are not used for non-sauce tests
        browserList = ImmutableList.of(new Object[] {
                (Supplier<DesiredCapabilities>) () -> LOCAL_RUN_CAPABILITIES, "Local JS test run"
        });
    }
    // For each browser, we need to run in and out of quirks mode.
    return browserList.stream()
            .flatMap((browser) ->
                    ImmutableList.of(new Object[] { browser[0], browser[1], false },
                                     new Object[] { browser[0], browser[1], true  }).stream())
            .collect(Collectors.toList());
}
 
Example #8
Source File: HUsToPickViewFactory.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public IView filterView(final IView view, final JSONFilterViewRequest filterViewRequest, Supplier<IViewsRepository> viewsRepo)
{
	final CreateViewRequest.Builder filterViewBuilder = CreateViewRequest.filterViewBuilder(view, filterViewRequest);

	if (view instanceof HUEditorView)
	{
		final HUEditorView huEditorView = HUEditorView.cast(view);
		filterViewBuilder.setParameters(huEditorView.getParameters());

		final ViewId parentViewId = huEditorView.getParentViewId();
		final IView parentView = viewsRepo.get().getView(parentViewId);
		if (parentView instanceof PickingSlotView)
		{
			final PickingSlotView pickingSlotView = PickingSlotView.cast(parentView);

			filterViewBuilder.setParameter(HUsToPickViewFilters.PARAM_CurrentShipmentScheduleId, pickingSlotView.getCurrentShipmentScheduleId());
		}
	}

	final CreateViewRequest createViewRequest = filterViewBuilder.build();

	return createView(createViewRequest);
}
 
Example #9
Source File: OidcIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
        AuthenticationRequestContext context) {
    ContextAwareTokenCredential credential = (ContextAwareTokenCredential) request.getToken();
    RoutingContext vertxContext = credential.getContext();
    return Uni.createFrom().deferred(new Supplier<Uni<SecurityIdentity>>() {
        @Override
        public Uni<SecurityIdentity> get() {
            if (tenantResolver.isBlocking(vertxContext)) {
                return context.runBlocking(new Supplier<SecurityIdentity>() {
                    @Override
                    public SecurityIdentity get() {
                        return authenticate(request, vertxContext).await().indefinitely();
                    }
                });
            }

            return authenticate(request, vertxContext);
        }
    });

}
 
Example #10
Source File: Message.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
/**
 * Create a message with the given payload and ack function.
 * No metadata are associated with the message.
 * Negative-acknowledgement is immediate.
 *
 * @param payload The payload, must not be {@code null}.
 * @param ack The ack function, this will be invoked when the returned messages {@link #ack()} method is invoked.
 * @param <T> the type of payload
 * @return A message with the given payload, no metadata and ack function.
 */
static <T> Message<T> of(T payload, Supplier<CompletionStage<Void>> ack) {
    if (payload == null) {
        throw new IllegalArgumentException("`payload` must not be `null`");
    }
    return new Message<T>() {
        @Override
        public T getPayload() {
            return payload;
        }

        @Override
        public Metadata getMetadata() {
            return Metadata.empty();
        }

        @Override
        public Supplier<CompletionStage<Void>> getAck() {
            return ack;
        }
    };
}
 
Example #11
Source File: CompletableFutureDemo.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
private String demoNoBlock() {
	CompletableFuture<String> resultCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
		public String get() {
			try {
				TimeUnit.SECONDS.sleep(6);
				//int i = 1/0; 如果有异常,则永远也不返回,即永远得不到结果
				System.out.println("执行线程:"+Thread.currentThread().getName());  
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "hello";
		}
	}, executor);

	resultCompletableFuture.thenAcceptAsync(new Consumer<String>() {  
	    @Override  
	    public void accept(String t) {  
	    System.out.println(t);  
	    System.out.println("回调线程:"+Thread.currentThread().getName());  
	    frame.setTitle(t);
	    }  
	}, executor);  
	System.out.println("直接不阻塞返回了######");  
	return "直接不阻塞返回了######";
}
 
Example #12
Source File: SessionHeartBeater.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public SessionHeartBeater(
   Partitioner partitioner,
   IntraServiceMessageBus intraServiceBus,
   Supplier<Stream<PartitionedSession>> sessionSupplier
) {
   this.sessionSupplier = sessionSupplier;
   this.partitioner = partitioner;
   this.intraServiceBus = intraServiceBus;
   this.executor = Executors
      .newSingleThreadScheduledExecutor(
         ThreadPoolBuilder
            .defaultFactoryBuilder()
            .setNameFormat("ipcd-session-heartbeat")
            .build()
      );
   this.heartbeatTimer = IrisMetrics.metrics("bridge.ipcd").timer("heartbeat");
}
 
Example #13
Source File: RelationAdapter.java    From webanno with Apache License 2.0 6 votes vote down vote up
public RelationAdapter(LayerSupportRegistry aLayerSupportRegistry,
        FeatureSupportRegistry aFeatureSupportRegistry,
        ApplicationEventPublisher aEventPublisher, AnnotationLayer aLayer,
        String aTargetFeatureName, String aSourceFeatureName,
        Supplier<Collection<AnnotationFeature>> aFeatures,
        List<RelationLayerBehavior> aBehaviors)
{
    super(aLayerSupportRegistry, aFeatureSupportRegistry, aEventPublisher, aLayer, aFeatures);
    
    if (aBehaviors == null) {
        behaviors = emptyList();
    }
    else {
        List<RelationLayerBehavior> temp = new ArrayList<>(aBehaviors);
        AnnotationAwareOrderComparator.sort(temp);
        behaviors = temp;
    }
    
    sourceFeatureName = aSourceFeatureName;
    targetFeatureName = aTargetFeatureName;
}
 
Example #14
Source File: AsyncRSPartitionAndSplittingTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void testPartition() {
	Supplier<ReactiveSeq<Integer>> s = () -> of(1, 2, 3, 4, 5, 6);

	assertEquals(asList(1, 3, 5), s.get().partition(i -> i % 2 != 0)._1().toList());
	assertEquals(asList(2, 4, 6), s.get().partition(i -> i % 2 != 0)._2().toList());

	assertEquals(asList(2, 4, 6), s.get().partition(i -> i % 2 == 0)._1().toList());
	assertEquals(asList(1, 3, 5), s.get().partition(i -> i % 2 == 0)._2().toList());

	assertEquals(asList(1, 2, 3), s.get().partition(i -> i <= 3)._1().toList());
	assertEquals(asList(4, 5, 6), s.get().partition(i -> i <= 3)._2().toList());

	assertEquals(asList(1, 2, 3, 4, 5, 6), s.get().partition(i -> true)._1().toList());
	assertEquals(asList(), s.get().partition(i -> true)._2().toList());

	assertEquals(asList(), s.get().partition(i -> false)._1().toList());
	assertEquals(asList(1, 2, 3, 4, 5, 6), s.get().partition(i -> false)._2().toList());
}
 
Example #15
Source File: SubStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldExecuteSubStepWithParameters()
{
    @SuppressWarnings("unchecked")
    Supplier<String> parameterProvider = mock(Supplier.class);
    when(parameterProvider.get()).thenReturn("parameters");
    StepResult stepResult = mock(StepResult.class);
    Step compositeStep = mock(Step.class);
    when(step.getComposedSteps()).thenReturn(List.of(compositeStep, compositeStep));
    when(compositeStep.perform(storyReporter, null)).thenReturn(stepResult);
    InOrder ordered = inOrder(subStepsListener, step, parameterProvider, stepResult);
    when(step.perform(storyReporter, null)).thenReturn(stepResult);
    Keywords keywords = mock(Keywords.class);
    when(configuration.keywords()).thenReturn(keywords);
    when(step.asString(keywords)).thenReturn("step");
    subSteps.execute(Optional.of(parameterProvider));

    ordered.verify(subStepsListener).beforeSubSteps();
    ordered.verify(parameterProvider).get();
    ordered.verify(stepResult).withParameterValues("step [parameters]");
    ordered.verify(stepResult).describeTo(storyReporter);
    ordered.verify(subStepsListener).afterSubSteps();
    ordered.verifyNoMoreInteractions();
}
 
Example #16
Source File: ReduceOps.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a {@code TerminalOp} that implements a mutable reduce on
 * {@code double} values.
 *
 * @param <R> the type of the result
 * @param supplier a factory to produce a new accumulator of the result type
 * @param accumulator a function to incorporate an int into an
 *        accumulator
 * @param combiner a function to combine an accumulator into another
 * @return a {@code TerminalOp} implementing the reduction
 */
public static <R> TerminalOp<Double, R>
makeDouble(Supplier<R> supplier,
           ObjDoubleConsumer<R> accumulator,
           BinaryOperator<R> combiner) {
    Objects.requireNonNull(supplier);
    Objects.requireNonNull(accumulator);
    Objects.requireNonNull(combiner);
    class ReducingSink extends Box<R>
            implements AccumulatingSink<Double, R, ReducingSink>, Sink.OfDouble {
        @Override
        public void begin(long size) {
            state = supplier.get();
        }

        @Override
        public void accept(double t) {
            accumulator.accept(state, t);
        }

        @Override
        public void combine(ReducingSink other) {
            state = combiner.apply(state, other.state);
        }
    }
    return new ReduceOp<Double, R, ReducingSink>(StreamShape.DOUBLE_VALUE) {
        @Override
        public ReducingSink makeSink() {
            return new ReducingSink();
        }
    };
}
 
Example #17
Source File: AbtractClusterFutureBuilder.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
public Supplier<List<NetworkOperationFuture>> getSupplier() {
	
	if(clusterOperationType == ClusterOperationType.READ_FROM_NODES_HA_IF_REPLICATED) {
		return getReplicatedSupplier();
	} else {
		return getUnreplicatedSupplier();
	}
}
 
Example #18
Source File: StartupConfiguration.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
StartupConfiguration(Supplier<NodeContext> nodeContextSupplier, boolean unConfigured, boolean repairMode, ClassLoader classLoader, PathResolver pathResolver, IParameterSubstitutor substitutor, ObjectMapperFactory objectMapperFactory) {
  this.nodeContextSupplier = requireNonNull(nodeContextSupplier);
  this.unConfigured = unConfigured;
  this.repairMode = repairMode;
  this.classLoader = requireNonNull(classLoader);
  this.pathResolver = requireNonNull(pathResolver);
  this.substitutor = requireNonNull(substitutor);
  this.objectMapper = objectMapperFactory.create();
}
 
Example #19
Source File: StoredNodeFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
private V decodeValue(final RLPInput valueRlp, final Supplier<String> errMessage) {
  final Bytes bytes;
  try {
    bytes = valueRlp.readBytes();
  } catch (final RLPException ex) {
    throw new MerkleTrieException(
        errMessage.get() + ": failed decoding value rlp " + valueRlp, ex);
  }
  return deserializeValue(errMessage, bytes);
}
 
Example #20
Source File: Logger_common_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * @param msgSupplier
 *          A function, which when called, produces the desired log message
 * @param throwable
 *          the exception to log
 */
@Override
public void info(Supplier<String> msgSupplier, Throwable throwable) {
  if (isLoggable(Level.INFO) && isNotLimited(Level.INFO)) {
    log2(null, fqcnCmn, Level.INFO, msgSupplier.get(), null, throwable);
  }
}
 
Example #21
Source File: ShowLogPatternParserEditor.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public ShowLogPatternParserEditor(OtrosApplication otrosApplication,
                                  String logPatternResourceName,
                                  String actionName,
                                  String shortDescription,
                                  Icon icon, Supplier<LogPatternParserEditorBase> viewSupplier) {
  super(otrosApplication);
  this.viewSupplier = viewSupplier;
  putValue(NAME, actionName);
  putValue(SHORT_DESCRIPTION, shortDescription);
  putValue(SMALL_ICON, icon);
  logPatternText = loadDefaultText(logPatternResourceName);

}
 
Example #22
Source File: ActorTimerExecuterService.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledFuture<?> schedule(final Supplier<ActorMessage<?>> supplier, final ActorGroup group, long initalDelay, long period, TimeUnit unit) {
	return timerExecuterService.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			ActorMessage<?> message = supplier.get();
			for (UUID id : group) {
				message.dest = id;
				system.send(message);
			}
		}
	}, initalDelay, period, unit); 
}
 
Example #23
Source File: Documenter.java    From moduliths with Apache License 2.0 5 votes vote down vote up
private void addComponentsToView(Supplier<Stream<Module>> modules, ComponentView view, Options options,
		Consumer<ComponentView> afterCleanup) {

	modules.get().filter(options.getExclusions().negate()) //
			.map(it -> getComponents(options).get(it)) //
			.filter(options.getComponentFilter()).forEach(view::add);

	// Remove filtered dependency types
	DependencyType.allBut(options.getDependencyTypes()) //
			.map(Object::toString) //
			.forEach(it -> view.removeRelationshipsWithTag(it));

	afterCleanup.accept(view);

	// Filter outgoing relationships of target-only modules
	modules.get().filter(options.getTargetOnly()) //
			.forEach(module -> {

				Component component = getComponents(options).get(module);

				view.getRelationships().stream() //
						.map(RelationshipView::getRelationship) //
						.filter(it -> it.getSource().equals(component)) //
						.forEach(it -> view.remove(it));
			});

	// … as well as all elements left without a relationship
	view.removeElementsWithNoRelationships();

	afterCleanup.accept(view);

	// Remove default relationships if more qualified ones exist
	view.getRelationships().stream() //
			.map(RelationshipView::getRelationship) //
			.collect(Collectors.groupingBy(Connection::of)) //
			.values().stream() //
			.forEach(it -> potentiallyRemoveDefaultRelationship(view, it));
}
 
Example #24
Source File: ForgeConfigSpec.java    From patchwork-api with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ValueSpec(Supplier<?> supplier, Predicate<Object> validator, BuilderContext context) {
	Objects.requireNonNull(supplier, "Default supplier can not be null");
	Objects.requireNonNull(validator, "Validator can not be null");

	this.comment = context.hasComment() ? context.buildComment() : null;
	this.langKey = context.getTranslationKey();
	this.range = context.getRange();
	this.worldRestart = context.needsWorldRestart();
	this.clazz = context.getClazz();
	this.supplier = supplier;
	this.validator = validator;
}
 
Example #25
Source File: ConnectionTest.java    From ndbc with Apache License 2.0 5 votes vote down vote up
@Test
public void isValidTrue() throws CheckedFutureException {
  final List<Row> result = new ArrayList<>();
  final String query = "SELECT 1";
  final Supplier<Connection> sup = new ConnectionSupplier() {
    @Override
    BiFunction<String, List<Value<?>>, Exchange<List<Row>>> extendedQueryExchange() {
      return (q, b) -> {
        assertEquals(query, q);
        return Exchange.value(result);
      };
    }
  };
  assertEquals(true, sup.get().isValid().get(timeout));
}
 
Example #26
Source File: JavaKit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void initDocument(BaseDocument doc) {
//        doc.addLayer(new JavaDrawLayerFactory.JavaLayer(),
//                JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY);
        doc.putProperty(SyntaxUpdateTokens.class,
              new SyntaxUpdateTokens() {
                  
                  private List tokenList = new ArrayList();
                  
                  public void syntaxUpdateStart() {
                      tokenList.clear();
                  }
      
                  public List syntaxUpdateEnd() {
                      return tokenList;
                  }
      
                  public void syntaxUpdateToken(TokenID id, TokenContextPath contextPath, int offset, int length) {
                      if (JavaTokenContext.LINE_COMMENT == id) {
                          tokenList.add(new TokenInfo(id, contextPath, offset, length));
                      }
                  }
              }
          );
        InputAttributes attrs = new InputAttributes();
        attrs.setValue(JavaTokenId.language(), "fileName", (Supplier<String>) () -> { //NOI18N
            FileObject fo = NbEditorUtilities.getFileObject(doc);
            return fo != null ? fo.getNameExt() : null;
        }, true);
        attrs.setValue(JavaTokenId.language(), "version", (Supplier<String>) () -> { //NOI18N
            return getSourceLevel(doc);
        }, true);
        doc.putProperty(InputAttributes.class, attrs);
      }
 
Example #27
Source File: JSONCache.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getOrCacheString(DataID dataID, UUID serverUUID, Supplier<String> stringSupplier) {
    String identifier = dataID.of(serverUUID);
    byte[] found = cache.getIfPresent(identifier);
    if (found == null) {
        String result = stringSupplier.get();
        cache.put(identifier, result.getBytes(StandardCharsets.UTF_8));
        return result;
    }
    return new String(found, StandardCharsets.UTF_8);
}
 
Example #28
Source File: ServerRestartTests.java    From ratis with Apache License 2.0 5 votes vote down vote up
static void writeSomething(Supplier<Message> newMessage, MiniRaftCluster cluster) throws Exception {
  try(final RaftClient client = cluster.createClient()) {
    // write some messages
    for(int i = 0; i < 10; i++) {
      Assert.assertTrue(client.send(newMessage.get()).isSuccess());
    }
  }
}
 
Example #29
Source File: Wrappers.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public static <T> Optional<T> optionally(Supplier<T> s) {
    try {
        return Optional.ofNullable(s.get());
    } catch (EmptyResultDataAccessException | IllegalArgumentException | IllegalStateException e) {
        return Optional.empty();
    }
}
 
Example #30
Source File: RegistryClientTest.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@RegistryServiceTest
public void testSmoke(Supplier<RegistryService> supplier) {
    RegistryService service = supplier.get();

    service.deleteAllGlobalRules();

    Assertions.assertNotNull(service.toString());
    Assertions.assertEquals(service.hashCode(), service.hashCode());
    Assertions.assertEquals(service, service);
}