SourceLevelSelector( @NonNull final PropertyEvaluator eval, @NonNull final String sourceLevelPropName, @NonNull final List<? extends Supplier<? extends ClassPath>> cpFactories) { Parameters.notNull("eval", eval); //NOI18N Parameters.notNull("sourceLevelPropName", sourceLevelPropName); //NOI18N Parameters.notNull("cpFactories", cpFactories); //NOI18N if (cpFactories.size() != 2) { throw new IllegalArgumentException("Invalid classpaths: " + cpFactories); //NOI18N } for (Supplier<?> f : cpFactories) { if (f == null) { throw new NullPointerException("Classpaths contain null: " + cpFactories); //NOI18N } } this.eval = eval; this.sourceLevelPropName = sourceLevelPropName; this.cpfs = cpFactories; this.listeners = new PropertyChangeSupport(this); this.cps = new ClassPath[2]; this.eval.addPropertyChangeListener(WeakListeners.propertyChange(this, this.eval)); }
/** * Computes applicable events. * * @param <AggregateT> The aggregate over which the query executes * @param <EventIdT> The type of the {@link EventT}'s id field * @param <EventT> The type of the Event * @param <SnapshotIdT> The type of the {@link SnapshotT}'s id field * @param <SnapshotT> The type of the Snapshot * @param forwardOnlyEvents Known forward only events * @param executor An instance of Executor * @param snapshotAndEventsSince Events to use if forwardOnlyEvents is empty * * @return events that can be applied. */ public static < AggregateT, EventIdT, EventT extends BaseEvent<AggregateT, EventIdT, EventT>, SnapshotIdT, SnapshotT extends BaseSnapshot<AggregateT, SnapshotIdT, EventIdT, EventT> > Flowable<EventT> getApplicableEvents( Flowable<EventT> forwardOnlyEvents, Executor executor, Supplier<Flowable<Pair<SnapshotT, List<EventT>>>> snapshotAndEventsSince) { return forwardOnlyEvents .filter(e -> e instanceof Deprecates) .toList() .toFlowable() .flatMap(list -> list.isEmpty() ? forwardOnlyEvents : snapshotAndEventsSince.get().flatMap(p -> getForwardOnlyEvents(p.getSecond(), executor, () -> error(new GroovesException( "Couldn't apply deprecates events"))) )); }
/** * Method for Performance Rate Uuid validations * * @param check a property existence check * @param keys that identify measures * @return a callback / consumer that will perform a measure specific validation against a given * node. */ private Consumer<Node> makePerformanceRateUuidValidator(Supplier<String> check, String... keys) { return node -> { if (check.get() != null) { Predicate<Node> childUuidFinder = makeUuidChildFinder(check, ErrorCode.QUALITY_MEASURE_ID_MISSING_SINGLE_PERFORMANCE_RATE, PERFORMANCE_RATE_ID); Node existingUuidChild = node .getChildNodes(TemplateId.PERFORMANCE_RATE_PROPORTION_MEASURE) .filter(childUuidFinder) .findFirst() .orElse(null); if (existingUuidChild == null) { addMeasureConfigurationValidationMessage(check, keys, node); } } }; }
@Test public void testGenerator() { final String prefix1 = "http://example.org/"; final String prefix2 = "trellis:repository/a/b/c/"; final IdentifierService svc = new UUIDGenerator(); final Supplier<String> gen1 = svc.getSupplier(prefix1); final Supplier<String> gen2 = svc.getSupplier(prefix2); final String id1 = gen1.get(); final String id2 = gen2.get(); assertTrue(id1.startsWith(prefix1)); assertFalse(id1.equals(prefix1)); assertTrue(id2.startsWith(prefix2)); assertFalse(id2.equals(prefix2)); }
/** * Applies the {@code pageMapper} function on each page fetched from the supplied {@code queryRequestSupplier} on * the supplied {@code ctpClient}. * * @param ctpClient defines the CTP project to apply the query on. * @param queryRequestSupplier defines a supplier which, when executed, returns the query that should be made on * the CTP project. * @param resourceMapper defines a mapper function that should be applied on each resource in the fetched page * from the query on the specified CTP project. */ public static <T extends Resource, C extends QueryDsl<T, C>> void queryAndApply( @Nonnull final SphereClient ctpClient, @Nonnull final Supplier<QueryDsl<T, C>> queryRequestSupplier, @Nonnull final Function<T, SphereRequest<T>> resourceMapper) { final Function<List<T>, Stream<CompletableFuture<T>>> pageMapper = pageElements -> pageElements.stream() .map(resourceMapper) .map(ctpClient::execute) .map(CompletionStage::toCompletableFuture); CtpQueryUtils.queryAll(ctpClient, queryRequestSupplier.get(), pageMapper) .thenApply(list -> list.stream().flatMap(Function.identity())) .thenApply(stream -> stream.toArray(CompletableFuture[]::new)) .thenCompose(CompletableFuture::allOf) .toCompletableFuture().join(); }
@DataProvider(name="maps") static Object[][] mapCases() { if (collections != null) { return collections; } List<Object[]> cases = new ArrayList<>(); for (int size : new int[] {1, 2, 16}) { cases.add(new Object[] { String.format("new HashMap(%d)", size), (Supplier<Map<Integer, Integer>>) () -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) }); cases.add(new Object[] { String.format("new TreeMap(%d)", size), (Supplier<Map<Integer, Integer>>) () -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) }); } return cases.toArray(new Object[0][]); }
@Override protected void registerItem(EndpointsEntry entry, MethodSpec.Builder methodBuilder) { final FullClassName handlerEndpoint = new FullClassName(entry.element.fullQualifiedNoneGenericName() + "EndpointHandler"); String path = entry.element.getAnnotation(Handler.class).value(); ClassName handlerEndpointType = ClassName.get(handlerEndpoint.asPackage(), handlerEndpoint.asSimpleName()); MethodSpec getMethod = MethodSpec.methodBuilder("get") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .returns(handlerEndpointType) .addStatement("return new $T()", handlerEndpointType) .build(); TypeSpec factoryType = TypeSpec.anonymousClassBuilder("") .addSuperinterface(ParameterizedTypeName.get(ClassName.get(Supplier.class), handlerEndpointType.box())) .addMethod(getMethod) .build(); methodBuilder.addStatement("registry.registerEndpoint(\"" + path + "\", $L)", factoryType); }
@Test public void testSubNetworkInterfaces() throws SocketException { Supplier<Stream<NetworkInterface>> ss = () -> { try { return allNetworkInterfaces(); } catch (SocketException e) { throw new RuntimeException(e); } }; Collection<NetworkInterface> expected = getAllNetworkInterfaces(); withData(TestData.Factory.ofSupplier("All network interfaces", ss)) .stream(s -> s) .expectedResult(expected) .exercise(); }
@Test public void testNetworkInterfaces() throws SocketException { Supplier<Stream<NetworkInterface>> ss = () -> { try { return NetworkInterface.networkInterfaces() .filter(ni -> isIncluded(ni)); } catch (SocketException e) { throw new RuntimeException(e); } }; Collection<NetworkInterface> enums = Collections.list(NetworkInterface.getNetworkInterfaces()); Collection<NetworkInterface> expected = new ArrayList<>(); enums.forEach(ni -> { if (isIncluded(ni)) { expected.add(ni); } }); withData(TestData.Factory.ofSupplier("Top-level network interfaces", ss)) .stream(s -> s) .expectedResult(expected) .exercise(); }
@Test(expected = IllegalStateException.class) public void testMismatchingUsedVariablesAndVariableDefinitions() { Supplier<InputStream> sourceFile = () -> SmtEncoderTest.class.getResourceAsStream( "spec_freevariable.xml"); ValidSpecification spec = TestUtils.importValidSpec(sourceFile.get(), new TypeEnum( "Color", Arrays.asList("red", "green", "blue"))); List<ValidFreeVariable> freeVariables = TestUtils.importValidFreeVariables(sourceFile.get(), new TypeEnum("Color", Arrays.asList("red", "green", "blue"))); int maxDuration = 5; SmtEncoder smtEncoder = new SmtEncoder(maxDuration, spec, Collections.emptyList()); SmtModel output = smtEncoder.getConstraint(); List<SExpression> constraints = output.getGlobalConstraints(); Collection<SExpression> definitions = output.getVariableDefinitions(); }
private void buildRefreshModelChain() { Supplier<Set<StackData>> stacksSupplier = new DataSourceStacksSupplier(commonDaoFacade, appName); TaskFactory taskFactory = new TaskFactory(DataSource.DATA_STORE); refreshModelChain = new TaskChain( new InitDataStoreTask(modelFacade)) .and(taskFactory.newGetFlavorRules()) .and(taskFactory.newGetUrlRules()) .and(taskFactory.newGetWhitelistedStacks()) .and(taskFactory.newGetNamespacedLists()) .and(taskFactory.newGetStacksWithHostsTask(stacksSupplier)) .and(taskFactory.newBackupStacksInMemory()) .and(taskFactory.newValidateAbleToRedirectTask()) .and(taskFactory.newApplyNewModelTask()); if (isStaticDiscoveryNeededForApp.test(appName)) { refreshModelChain.and(new TriggerManualBackupTask(stacksBackupManager)); } refreshModelChain.and(new BackupNewModelTask(flavorRulesHolder, whiteListHolder, urlRulesHolder, modelMetadataHolder)); }
@Test public void allStringJoins() { List<Supplier<Refactor.LongTrackFinder>> finders = Arrays.<Supplier<Refactor.LongTrackFinder>>asList( Refactor.Step0::new, Refactor.Step1::new, Refactor.Step2::new, Refactor.Step3::new, Refactor.Step4::new ); List<Album> albums = unmodifiableList(asList(SampleData.aLoveSupreme, SampleData.sampleShortAlbum)); List<Album> noTracks = unmodifiableList(asList(SampleData.sampleShortAlbum)); finders.forEach(finder -> { System.out.println("Testing: " + finder.toString()); Refactor.LongTrackFinder longTrackFinder = finder.get(); Set<String> longTracks = longTrackFinder.findLongTracks(albums); assertEquals("[Acknowledgement, Resolution]", longTracks.toString()); longTracks = longTrackFinder.findLongTracks(noTracks); assertTrue(longTracks.isEmpty()); }); }
@Test public void testUnawaitedBackgroundWorkShouldCompleteWithoutSyncBlock() throws Exception { CompletableFuture<Void> unawaitedWorkCompleted = new CompletableFuture<>(); Supplier<CompletableFuture<Void>> otherAsyncMethod = ExecutionContext.wrap(() -> { StrongBox<CompletableFuture<Void>> result = new StrongBox<>(); Consumer<Void> implementation = ignored -> result.value = Async.awaitAsync( // this posts to the JoinableTask.threadPoolQueue Async.yieldAsync(), () -> Async.awaitAsync( // this should schedule directly to the .NET ThreadPool. Async.yieldAsync(), () -> { unawaitedWorkCompleted.complete(null); return Futures.completedNull(); })); ExecutionContext.run(ExecutionContext.capture(), implementation, null); return result.value; }); CompletableFuture<Void> bkgrndThread = Futures.runAsync(() -> { asyncPump.run(() -> { TplExtensions.forget(otherAsyncMethod.get()); return Futures.completedNull(); }); }); bkgrndThread.join(); unawaitedWorkCompleted.get(EXPECTED_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); }
@Override public void maybeAssignManifoldType( ClassLoader loader, String fqn, URL url, BiConsumer<String, Supplier<byte[]>> assigner ) { Set<ITypeManifold> sps = getCurrentModule().findTypeManifoldsFor( fqn ); if( !sps.isEmpty() ) { assigner.accept( fqn, null ); } }
protected <T> CompletableFuture<T> delayedException (final long delay, final Supplier<Exception> exceptionSupplier) { final CompletableFuture<T> future = new CompletableFuture<>(); rule.vertx().setTimer(delay, l -> rule.vertx().runOnContext(v -> { future.completeExceptionally(exceptionSupplier.get()); })); return future; }
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) { return new Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>>() { @Override public Supplier<ImmutableMap.Builder<K, V>> supplier() { return ImmutableMap::builder; } @Override public BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator() { return (builder, t) -> { final V value = valueMapper.apply(t); if(value != null) { builder.put(keyMapper.apply(t), value); } }; } @Override public BinaryOperator<ImmutableMap.Builder<K, V>> combiner() { return (b1, b2) -> { b1.putAll(b2.build()); return b1; }; } @Override public Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher() { return ImmutableMap.Builder::build; } @Override public Set<Characteristics> characteristics() { return emptySet(); } }; }
public static void main(String[] args) { Supplier<String> s1 = new T8134329() { }::m; assertEquals(s1.get(), "m"); Supplier<String> s2 = new T8134329() { }::g; assertEquals(s2.get(), "g"); Supplier<String> s3 = new T8134329() { }::m; assertEquals(s3.get(), "m"); }
@Override public final void logp(PlatformLogger.Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier<String> msgSupplier) { if (isLoggable(level)) { publish(getCallerInfo(sourceClass, sourceMethod), logLevel(level), msgSupplier.get(), thrown); } }
/** * Convert user arguments to a Stream of snippets referenced by those * arguments (or lack of arguments). * * @param snippets the base list of possible snippets * @param defFilter the filter to apply to the arguments if no argument * @param rawargs the user's argument to the command, maybe be the empty * string * @return a Stream of referenced snippets or null if no matches are found */ private <T extends Snippet> Stream<T> argsOptionsToSnippets(Supplier<Stream<T>> snippetSupplier, Predicate<Snippet> defFilter, String rawargs, String cmd) { ArgTokenizer at = new ArgTokenizer(cmd, rawargs.trim()); at.allowedOptions("-all", "-start"); List<String> args = new ArrayList<>(); String s; while ((s = at.next()) != null) { args.add(s); } if (!checkOptionsAndRemainingInput(at)) { return null; } if (at.optionCount() > 0 && args.size() > 0) { errormsg("jshell.err.may.not.specify.options.and.snippets", at.whole()); return null; } if (at.optionCount() > 1) { errormsg("jshell.err.conflicting.options", at.whole()); return null; } if (at.hasOption("-all")) { // all snippets including start-up, failed, and overwritten return snippetSupplier.get(); } if (at.hasOption("-start")) { // start-up snippets return snippetSupplier.get() .filter(this::inStartUp); } if (args.isEmpty()) { // Default is all active user snippets return snippetSupplier.get() .filter(defFilter); } return argsToSnippets(snippetSupplier, args); }
@Test public void convertStringToDateRangeDriverAndTestDates() { final DriverCache cache = new DriverCache(); final String testString = "DR:2017-07-04T16:00:00.000Z|2017-07-10T16:00:00.000Z"; final Supplier<InputDriver> rangeSupplier = DomainSerialiser.createInputDriver(testString, cache); final InputDriver dateRangeDriver = rangeSupplier.get(); assertNotNull(dateRangeDriver); assertThat(dateRangeDriver.getType(), is(InputValueType.DATE_RANGE)); assertThat(dateRangeDriver.getValue(), is(testString)); assertThat(dateRangeDriver.evaluate("2017-07-04T16:00:00.000Z"), is(true)); assertThat(dateRangeDriver.evaluate("2017-07-10T16:00:00.000Z"), is(false)); }
public void testLevel(Levels level, java.lang.System.Logger logger, Supplier<String> msg, Throwable thrown) { Runnable test = () -> level.level(logger, msg, thrown); Checker<BackendRecord, Level> check = (res, l) -> { checkRecord(level, res, logger.getName(), l, msg, adaptor().getCallerClassName(level, Levels.class.getName()), adaptor().getCallerMethodName(level, "invoke"), thrown, null); return null; }; test("throw, msgSupplier", level, logger, test, check); }
@Override public Chain<T> orElseGet(Predicate<? super T> test, Supplier<? extends T> failSupplier) { Preconditions.checkNotNull(test, "test"); Preconditions.checkNotNull(failSupplier, "failSupplier"); if (!test.test(object)) { this.object = failSupplier.get(); } return this; }
@Test(dataProvider = "Source") public <T> void lateBindingTestWithCharacteritics(String description, Supplier<Source<T>> ss) { Source<T> source = ss.get(); Collection<T> c = source.asCollection(); Spliterator<T> s = c.spliterator(); s.characteristics(); Set<T> r = new HashSet<>(); s.forEachRemaining(r::add); assertEquals(r, new HashSet<>(c)); }
static void logAppendEntries(boolean isHeartbeat, Supplier<String> message) { if (isHeartbeat) { if (LOG.isTraceEnabled()) { LOG.trace("HEARTBEAT: " + message.get()); } } else { if (LOG.isDebugEnabled()) { LOG.debug(message.get()); } } }
private static <PK extends PrimaryKey<PK>,D extends Databean<PK,D>> D databeanFromJson(Supplier<D> databeanSupplier, DatabeanFielder<PK,D> fielder, JsonObject json, boolean flatKey){ if(json == null){ return null; } D databean = databeanSupplier.get(); JsonObject pkJson; if(flatKey){ pkJson = json; }else{ pkJson = json.getAsJsonObject(databean.getKeyFieldName()); } primaryKeyFromJson(databean.getKey(), fielder.getKeyFielder(), pkJson); List<Field<?>> fields = fielder.getNonKeyFields(databean); for(Field<?> field : fields){ String jsonFieldName = field.getKey().getColumnName(); JsonElement jsonValue = json.get(jsonFieldName); if(jsonValue == null || jsonValue.isJsonNull()){// careful: only skip nulls, not empty strings continue; } String valueString; if(jsonValue.isJsonObject()){ valueString = jsonValue.toString(); }else{ valueString = jsonValue.getAsString(); } Object value = field.parseStringEncodedValueButDoNotSet(valueString); field.setUsingReflection(databean, value); } return databean; }
/** * This implementation of type converter factory will pretty much allow implicit conversions of anything to anything * else that's allowed among JavaScript primitive types (string to number, boolean to string, etc.) * @param sourceType the type to convert from * @param targetType the type to convert to * @return a conditional converter from source to target type */ @Override public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) { final MethodHandle mh = JavaArgumentConverters.getConverter(targetType); if (mh == null) { if(targetType == Object.class && sourceType == void.class) { return VOID_TO_OBJECT; } return null; } return new GuardedInvocation(mh, canLinkTypeStatic(sourceType) ? null : GUARD_PRIMITIVE).asType(mh.type().changeParameterType(0, sourceType)); }
public SystemParametersBuilder(String platformName, String organization, String space, String user, String defaultDomain, PlatformType xsType, URL targetUrl, String authorizationEndpoint, String deployServiceUrl, int routerPort, boolean portBasedRouting, boolean reserveTemporaryRoutes, PortAllocator portAllocator, boolean useNamespaces, boolean useNamespacesForServices, DeployedMta deployedMta, int majorSchemaVersion, boolean areXsPlaceholdersSupported, XsPlaceholderResolver xsPlaceholderResolver, Supplier<String> timestampSupplier) { this(platformName, organization, space, user, defaultDomain, xsType, targetUrl, authorizationEndpoint, deployServiceUrl, routerPort, portBasedRouting, reserveTemporaryRoutes, portAllocator, useNamespaces, useNamespacesForServices, deployedMta, new CredentialsGenerator(), majorSchemaVersion, areXsPlaceholdersSupported, xsPlaceholderResolver, timestampSupplier); }
/** * Process a method argument; this method allows the caller to specify a custom speculative attribution * logic (this is used e.g. for lambdas). */ @SuppressWarnings("unchecked") <T extends JCExpression, Z extends ArgumentType<T>> void processArg(T that, Supplier<Z> argumentTypeFactory) { UniquePos pos = new UniquePos(that); Z cached = (Z)argumentTypeCache.get(pos); if (cached != null) { //dup existing speculative type setResult(that, cached.dup(that, env)); } else { Z res = argumentTypeFactory.get(); argumentTypeCache.put(pos, res); setResult(that, res); } }
/** * <p>Creates a binding using the passed supplier and list of dependencies.</p> * * <p>Note that this method requires manual implementation of the respective binding logic. For * most cases, however, the static methods provided by this interface do suffice however and * require far less manually programmed logic.</p> */ @Nonnull static <V> Binding<V> create(@Nonnull Supplier<V> supplier, ReadOnlyObservable<?>... observables) { return new AbstractBinding<V>(new HashSet<>(Arrays.asList(observables))) { @Override protected V compute() { return supplier.get(); } }; }
default AdvancedRunnable supply(Supplier<? extends T> supplier1, Supplier<? extends U> supplier2, Supplier<? extends V> supplier3) { Objects.requireNonNull(supplier1); Objects.requireNonNull(supplier2); Objects.requireNonNull(supplier3); return () -> accept(supplier1.get(), supplier2.get(), supplier3.get()); }
/** * 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(); } }; }
AbstractTestNodesAction(Settings settings, String actionName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, Supplier<NodesRequest> request, Supplier<NodeRequest> nodeRequest) { super(settings, actionName, threadPool, clusterService, transportService, new ActionFilters(new HashSet<>()), new IndexNameExpressionResolver(Settings.EMPTY), request, nodeRequest, ThreadPool.Names.GENERIC, NodeResponse.class); }
void testSpliterator(Supplier<Spliterator<Map.Entry<Integer, Integer>>> ss, // Higher order function that given a spliterator returns a // consumer for that spliterator which traverses elements // using an EntryConsumer Function<Spliterator<Map.Entry<Integer, Integer>>, Consumer<EntryConsumer>> sc) { testWithEntryConsumer(sc.apply(ss.get())); Spliterator<Map.Entry<Integer, Integer>> s = ss.get(); Spliterator<Map.Entry<Integer, Integer>> split = s.trySplit(); if (split != null) { testWithEntryConsumer(sc.apply(split)); testWithEntryConsumer(sc.apply(s)); } }
public static OfDouble ofDoubleSupplier(String name, Supplier<DoubleStream> supplier) { return new AbstractTestData.DoubleTestData<>(name, supplier, Supplier::get, s -> s.get().parallel(), s -> s.get().spliterator(), s -> (int) s.get().spliterator().getExactSizeIfKnown()); }
@Test public void trace_format_argSuppliers() throws Exception { lambdaLogger.trace("trace format", () -> "arg1", () -> "arg2", () -> "arg three"); verify(lambdaLogger).doLog(eq(null), eq(Level.TRACE), eq("trace format"), argSuppliersCaptor.capture(), eq(null)); Supplier[] suppliers = argSuppliersCaptor.getValue(); assertThat(suppliers.length).isEqualTo(3); assertThat(suppliers[0].get()).isEqualTo("arg1"); assertThat(suppliers[1].get()).isEqualTo("arg2"); assertThat(suppliers[2].get()).isEqualTo("arg three"); }
@DataProvider(name = "partOfPathDoesNotExist") public Object[][] partOfPathDoesNotExist() throws IOException { Path jmod = MODS_DIR.resolve("output.jmod"); FileUtils.deleteFileIfExistsWithRetry(jmod); FileUtils.deleteFileIfExistsWithRetry(Paths.get("doesNotExist")); Path emptyDir = Paths.get("empty"); if (Files.exists(emptyDir)) FileUtils.deleteFileTreeWithRetry(emptyDir); Files.createDirectory(emptyDir); List<Supplier<JmodResult>> tasks = Arrays.asList( () -> jmod("create", "--hash-modules", "anyPattern", "--module-path","empty" + pathSeparator + "doesNotExist", "output.jmod"), () -> jmod("create", "--class-path", "empty" + pathSeparator + "doesNotExist", "output.jmod"), () -> jmod("create", "--class-path", "empty" + pathSeparator + "doesNotExist.jar", "output.jmod"), () -> jmod("create", "--cmds", "empty" + pathSeparator + "doesNotExist", "output.jmod"), () -> jmod("create", "--config", "empty" + pathSeparator + "doesNotExist", "output.jmod"), () -> jmod("create", "--libs", "empty" + pathSeparator + "doesNotExist", "output.jmod") ); String errMsg = "Error: path not found: doesNotExist"; return tasks.stream().map(t -> new Object[] {t, errMsg} ) .toArray(Object[][]::new); }
@Test public void transactional() throws CheckedFutureException { final Integer result = 1; final Supplier<Future<Integer>> block = () -> Future.value(result); final Connection c = new TestConnection() { @Override public <R> Future<R> withTransaction(final Supplier<Future<R>> sup) { assertEquals(block, sup); return sup.get(); } }; assertEquals(result, ds(c).transactional(block).get(timeout)); }
UninstallNpmDependencyButtonListener(BiFunction<Collection<String>, IProgressMonitor, IStatus> uninstallAction, Supplier<IInputValidator> validator, StatusHelper statusHelper, Supplier<String> initalValue) { this.statusHelper = statusHelper; this.validator = validator; this.uninstallAction = uninstallAction; this.initalValue = initalValue; }
@Override public List<RestHandler> getRestHandlers(final Settings settings, final RestController restController, final ClusterSettings clusterSettings, final IndexScopedSettings indexScopedSettings, final SettingsFilter settingsFilter, final IndexNameExpressionResolver indexNameExpressionResolver, final Supplier<DiscoveryNodes> nodesInCluster) { return Arrays.asList(new RestIndexingProxyProcessAction(settings, restController, pluginComponent), new RestIndexingProxyRequestAction(settings, restController, pluginComponent)); }
@Override public Map<String, Supplier<UnicastHostsProvider>> getZenHostsProviders(TransportService transportService, NetworkService networkService) { return Collections.singletonMap( "file", () -> new FileBasedUnicastHostsProvider(settings, transportService, fileBasedDiscoveryExecutorService)); }