use of java.util.function.Consumer in project DiscLoader by R3alCl0ud.
the class Guild method fetchMembers.
@Override
public CompletableFuture<Map<Long, IGuildMember>> fetchMembers(int limit) {
CompletableFuture<Map<Long, IGuildMember>> future = new CompletableFuture<>();
final Consumer<GuildMembersChunkEvent> consumer = new Consumer<GuildMembersChunkEvent>() {
@Override
public void accept(GuildMembersChunkEvent e) {
if (e.getGuild().getID() != getID()) {
loader.onceEvent(GuildMembersChunkEvent.class, this);
return;
}
future.complete(e.getMembers());
}
};
loader.onceEvent(GuildMembersChunkEvent.class, consumer);
Packet payload = new Packet(8, new MemberQuery(limit, ""));
loader.socket.send(payload);
return future;
}
use of java.util.function.Consumer in project nifi by apache.
the class ZooKeeperMigrator method writeZooKeeper.
void writeZooKeeper(InputStream zkData, AuthMode authMode, byte[] authData, boolean ignoreSource, boolean useExistingACL) throws IOException, ExecutionException, InterruptedException {
// ensure that the chroot path exists
ZooKeeper zooKeeperRoot = getZooKeeper(Joiner.on(',').join(zooKeeperEndpointConfig.getServers()), authMode, authData);
ensureNodeExists(zooKeeperRoot, zooKeeperEndpointConfig.getPath(), CreateMode.PERSISTENT);
closeZooKeeper(zooKeeperRoot);
ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(zkData)));
Gson gson = new GsonBuilder().create();
jsonReader.beginArray();
// determine source ZooKeeperEndpointConfig for this data
final ZooKeeperEndpointConfig sourceZooKeeperEndpointConfig = gson.fromJson(jsonReader, ZooKeeperEndpointConfig.class);
LOGGER.info("Source data was obtained from ZooKeeper: {}", sourceZooKeeperEndpointConfig);
Preconditions.checkArgument(!Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getConnectString()) && !Strings.isNullOrEmpty(sourceZooKeeperEndpointConfig.getPath()) && sourceZooKeeperEndpointConfig.getServers() != null && sourceZooKeeperEndpointConfig.getServers().size() > 0, "Source ZooKeeper %s from %s is invalid", sourceZooKeeperEndpointConfig, zkData);
Preconditions.checkArgument(Collections.disjoint(zooKeeperEndpointConfig.getServers(), sourceZooKeeperEndpointConfig.getServers()) || !zooKeeperEndpointConfig.getPath().equals(sourceZooKeeperEndpointConfig.getPath()) || ignoreSource, "Source ZooKeeper config %s for the data provided can not contain the same server and path as the configured destination ZooKeeper config %s", sourceZooKeeperEndpointConfig, zooKeeperEndpointConfig);
// stream through each node read from the json input
final Stream<DataStatAclNode> stream = StreamSupport.stream(new Spliterators.AbstractSpliterator<DataStatAclNode>(0, 0) {
@Override
public boolean tryAdvance(Consumer<? super DataStatAclNode> action) {
try {
// stream each DataStatAclNode from configured json file
synchronized (jsonReader) {
if (jsonReader.hasNext()) {
action.accept(gson.fromJson(jsonReader, DataStatAclNode.class));
return true;
} else {
return false;
}
}
} catch (IOException e) {
throw new RuntimeException("unable to read nodes from json", e);
}
}
}, false);
final List<CompletableFuture<Stat>> writeFutures = stream.parallel().map(node -> {
/*
* create stage to determine the acls that should be applied to the node.
* this stage will be used to initialize the chain
*/
final CompletableFuture<List<ACL>> determineACLStage = CompletableFuture.supplyAsync(() -> determineACLs(node, authMode, useExistingACL));
/*
* create stage to apply acls to nodes and transform node to DataStatAclNode object
*/
final Function<List<ACL>, CompletableFuture<DataStatAclNode>> transformNodeStage = acls -> CompletableFuture.supplyAsync(() -> transformNode(node, acls));
/*
* create stage to ensure that nodes exist for the entire path of the zookeeper node, must be invoked after the transformNode stage to
* ensure that the node will exist after path migration
*/
final Function<DataStatAclNode, CompletionStage<String>> ensureNodeExistsStage = dataStatAclNode -> CompletableFuture.supplyAsync(() -> ensureNodeExists(zooKeeper, dataStatAclNode.getPath(), dataStatAclNode.getEphemeralOwner() == 0 ? CreateMode.PERSISTENT : CreateMode.EPHEMERAL));
/*
* create stage that waits for both the transformNode and ensureNodeExists stages complete, and also provides that the given transformed node is
* available to the next stage
*/
final BiFunction<String, DataStatAclNode, DataStatAclNode> combineEnsureNodeAndTransferNodeStage = (u, dataStatAclNode) -> dataStatAclNode;
/*
* create stage to transmit the node to the destination zookeeper endpoint, must be invoked after the node has been transformed and its path
* has been created (or already exists) in the destination zookeeper
*/
final Function<DataStatAclNode, CompletionStage<Stat>> transmitNodeStage = dataStatNode -> CompletableFuture.supplyAsync(() -> transmitNode(zooKeeper, dataStatNode));
/*
* submit the stages chained together in the proper order to perform the processing on the given node
*/
final CompletableFuture<DataStatAclNode> dataStatAclNodeCompletableFuture = determineACLStage.thenCompose(transformNodeStage);
return dataStatAclNodeCompletableFuture.thenCompose(ensureNodeExistsStage).thenCombine(dataStatAclNodeCompletableFuture, combineEnsureNodeAndTransferNodeStage).thenCompose(transmitNodeStage);
}).collect(Collectors.toList());
CompletableFuture<Void> allWritesFuture = CompletableFuture.allOf(writeFutures.toArray(new CompletableFuture[writeFutures.size()]));
final CompletableFuture<List<Stat>> finishedWrites = allWritesFuture.thenApply(v -> writeFutures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
final List<Stat> writesDone = finishedWrites.get();
if (LOGGER.isInfoEnabled()) {
final int writeCount = writesDone.size();
LOGGER.info("{} {} transferred to {}", writeCount, writeCount == 1 ? "node" : "nodes", zooKeeperEndpointConfig);
}
jsonReader.close();
closeZooKeeper(zooKeeper);
}
use of java.util.function.Consumer in project async-http-client by AsyncHttpClient.
the class EventPipelineTest method asyncPipelineTest.
@Test
public void asyncPipelineTest() throws Exception {
Consumer<Channel> httpAdditionalPipelineInitializer = channel -> channel.pipeline().addBefore("inflater", "copyEncodingHeader", new CopyEncodingHandler());
try (AsyncHttpClient p = asyncHttpClient(config().setHttpAdditionalChannelInitializer(httpAdditionalPipelineInitializer))) {
final CountDownLatch l = new CountDownLatch(1);
p.executeRequest(get(getTargetUrl()), new AsyncCompletionHandlerAdapter() {
@Override
public Response onCompleted(Response response) {
try {
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getHeader("X-Original-Content-Encoding"), "<original encoding>");
} finally {
l.countDown();
}
return response;
}
}).get();
if (!l.await(TIMEOUT, TimeUnit.SECONDS)) {
fail("Timeout out");
}
}
}
use of java.util.function.Consumer in project xtext-eclipse by eclipse.
the class JavaBuilderState method getQualifiedTypeNames.
private TypeNames getQualifiedTypeNames(final String typeLocator, final String packageName, final String simpleName, final IJavaProject project) {
TypeNames _xblockexpression = null;
{
final TypeNames qualifiedTypeNames = new TypeNames(project);
final String primaryTypeFqn = this.getQualifedTypeName(packageName, simpleName);
char[][] _definedTypeNamesFor = null;
if (this.state != null) {
_definedTypeNamesFor = this.state.getDefinedTypeNamesFor(typeLocator);
}
final char[][] typeNames = _definedTypeNamesFor;
if ((typeNames == null)) {
TypeNames _typeNames = new TypeNames(project);
final Procedure1<TypeNames> _function = (TypeNames it) -> {
it.addTypeName(primaryTypeFqn, primaryTypeFqn);
};
return ObjectExtensions.<TypeNames>operator_doubleArrow(_typeNames, _function);
}
final Consumer<char[]> _function_1 = (char[] it) -> {
String _string = new String(it);
final String typeName = this.getQualifedTypeName(packageName, _string);
qualifiedTypeNames.addTypeName(typeName, primaryTypeFqn);
};
((List<char[]>) Conversions.doWrapArray(typeNames)).forEach(_function_1);
_xblockexpression = qualifiedTypeNames;
}
return _xblockexpression;
}
use of java.util.function.Consumer in project Gargoyle by callakrsos.
the class FxUtil method newInstance.
private static <T, C> T newInstance(Class<?> controllerClass, Object rootInstance, boolean isSelfController, String _fxml, Consumer<T> option, Consumer<C> controllerAction) throws Exception {
String fxml = _fxml;
if (fxml == null) {
FXMLController controller = getFxmlController(controllerClass);
if (controller == null) {
throw new GargoyleException("this is not FXMLController. check @FXMLController");
}
//controller.value();
fxml = getFxml(controller);
}
URL resource = controllerClass.getResource(fxml);
FXMLLoader loader = createNewFxmlLoader();
loader.setLocation(resource);
if (isSelfController && rootInstance != null) {
try {
loader.setRoot(rootInstance);
loader.setController(rootInstance);
} catch (Exception e) {
throw new GargoyleException(e);
}
}
T load = loader.load();
C instanceController = loader.getController();
// show warning...
if (load == null) {
LOGGER.warn("load result is empty.. controller class : {} ", controllerClass);
}
Method[] declaredMethods = controllerClass.getDeclaredMethods();
// 2017-02-07 findfirst에서 어노테이션으로 선언된 다건의 함수를 호출하게 다시 유도.
// findfirst로 수정. @FxPostInitialize가 여러건있는경우를 잘못된 로직 유도를 방지.
Stream.of(declaredMethods).filter(m -> m.getParameterCount() == 0 && m.getAnnotation(FxPostInitialize.class) != null).forEach(m -> {
if (m.getModifiers() == Modifier.PUBLIC) {
try {
if (instanceController != null) {
Platform.runLater(() -> {
try {
m.setAccessible(true);
m.invoke(instanceController);
} catch (Exception e) {
LOGGER.error(ValueUtil.toString(e));
}
});
}
} catch (Exception e) {
LOGGER.error(ValueUtil.toString(e));
}
}
});
if (option != null) {
option.accept(load);
}
if (controllerAction != null)
controllerAction.accept(instanceController);
Platform.runLater(() -> {
Parent parent = (Parent) load;
List<Node> findAllByNodes = FxUtil.findAllByNodes(parent, v -> v instanceof Button);
findAllByNodes.forEach(v -> {
GargoyleButtonBuilder.applyStyleClass((Button) v, SkinManager.BUTTON_STYLE_CLASS_NAME);
});
});
return load;
}
Aggregations