Search in sources :

Example 56 with Consumer

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;
}
Also used : Packet(io.discloader.discloader.entity.sendable.Packet) CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(java.util.function.Consumer) GuildMembersChunkEvent(io.discloader.discloader.common.event.guild.member.GuildMembersChunkEvent) Map(java.util.Map) HashMap(java.util.HashMap)

Example 57 with Consumer

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);
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) Spliterators(java.util.Spliterators) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) ACL(org.apache.zookeeper.data.ACL) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) JsonParser(com.google.gson.JsonParser) Function(java.util.function.Function) GsonBuilder(com.google.gson.GsonBuilder) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Gson(com.google.gson.Gson) OutputStreamWriter(java.io.OutputStreamWriter) StreamSupport(java.util.stream.StreamSupport) Splitter(com.google.common.base.Splitter) JsonWriter(com.google.gson.stream.JsonWriter) ZooKeeper(org.apache.zookeeper.ZooKeeper) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Watcher(org.apache.zookeeper.Watcher) BufferedWriter(java.io.BufferedWriter) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) ZooDefs(org.apache.zookeeper.ZooDefs) Preconditions(com.google.common.base.Preconditions) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) Joiner(com.google.common.base.Joiner) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) List(java.util.List) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) ACL(org.apache.zookeeper.data.ACL) IOException(java.io.IOException) Spliterators(java.util.Spliterators) ZooKeeper(org.apache.zookeeper.ZooKeeper) BiFunction(java.util.function.BiFunction) BufferedReader(java.io.BufferedReader)

Example 58 with Consumer

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");
        }
    }
}
Also used : AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) Assert.fail(org.testng.Assert.fail) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) Response(org.asynchttpclient.Response) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) Dsl(org.asynchttpclient.Dsl) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest) Response(org.asynchttpclient.Response) Channel(io.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) Test(org.testng.annotations.Test) AbstractBasicTest(org.asynchttpclient.AbstractBasicTest)

Example 59 with Consumer

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;
}
Also used : TypeNames(org.eclipse.xtext.common.types.ui.notification.TypeNames) Consumer(java.util.function.Consumer) Procedure1(org.eclipse.xtext.xbase.lib.Procedures.Procedure1)

Example 60 with Consumer

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;
}
Also used : StageStyle(javafx.stage.StageStyle) PageOrientation(javafx.print.PageOrientation) Printer(javafx.print.Printer) SnapshotParameters(javafx.scene.SnapshotParameters) Transition(javafx.animation.Transition) AnimationType(jidefx.animation.AnimationType) PageLayout(javafx.print.PageLayout) TabPane(javafx.scene.control.TabPane) FontPosture(javafx.scene.text.FontPosture) Map(java.util.Map) Point2D(javafx.geometry.Point2D) PopOver(org.controlsfx.control.PopOver) Rectangle2D(javafx.geometry.Rectangle2D) Pair(javafx.util.Pair) Set(java.util.Set) SnapshotResult(javafx.scene.SnapshotResult) KeyEvent(javafx.scene.input.KeyEvent) Screen(javafx.stage.Screen) ScmCommitComposite(com.kyj.fx.voeditor.visual.component.scm.ScmCommitComposite) Platform(javafx.application.Platform) Stream(java.util.stream.Stream) Region(javafx.scene.layout.Region) FxContextManager(com.kyj.fx.voeditor.visual.framework.contextmenu.FxContextManager) ObservableList(javafx.collections.ObservableList) BorderPane(javafx.scene.layout.BorderPane) MouseButton(javafx.scene.input.MouseButton) TreeItem(javafx.scene.control.TreeItem) DockNode(com.kyj.fx.voeditor.visual.component.dock.pane.DockNode) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) FXMLLoader(javafx.fxml.FXMLLoader) GargoyleButtonBuilder(com.kyj.fx.voeditor.visual.framework.builder.GargoyleButtonBuilder) Color(javafx.scene.paint.Color) Properties(java.util.Properties) TitledPane(javafx.scene.control.TitledPane) Node(javafx.scene.Node) PopupFeatures(javafx.scene.web.PopupFeatures) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) FileChooser(javafx.stage.FileChooser) Tab(javafx.scene.control.Tab) ImageView(javafx.scene.image.ImageView) ObservableValue(javafx.beans.value.ObservableValue) SkinManager(com.kyj.fx.voeditor.visual.momory.SkinManager) Image(javafx.scene.image.Image) Button(javafx.scene.control.Button) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) JavaTextArea(com.kyj.fx.voeditor.visual.component.text.JavaTextArea) ToExcelFileFunction(com.kyj.fx.voeditor.visual.functions.ToExcelFileFunction) WebEvent(javafx.scene.web.WebEvent) JavaSVNManager(com.kyj.scm.manager.svn.java.JavaSVNManager) SvnChagnedCodeComposite(com.kyj.fx.voeditor.visual.component.scm.SvnChagnedCodeComposite) Parent(javafx.scene.Parent) FileSystemView(javax.swing.filechooser.FileSystemView) Task(javafx.concurrent.Task) InstanceTypes(com.kyj.fx.voeditor.visual.framework.InstanceTypes) ImageIO(javax.imageio.ImageIO) WindowEvent(javafx.stage.WindowEvent) TableView(javafx.scene.control.TableView) Method(java.lang.reflect.Method) AutoCompletionTextFieldBinding(impl.org.controlsfx.autocompletion.AutoCompletionTextFieldBinding) FxSVNHistoryDataSupplier(com.kyj.fx.voeditor.visual.component.scm.FxSVNHistoryDataSupplier) TextField(javafx.scene.control.TextField) GargoyleLoadBar(com.kyj.fx.voeditor.visual.component.bar.GargoyleLoadBar) Paper(javafx.print.Paper) BufferedImage(java.awt.image.BufferedImage) Predicate(java.util.function.Predicate) FXMLController(com.kyj.fx.voeditor.visual.framework.annotation.FXMLController) Font(javafx.scene.text.Font) Icon(javax.swing.Icon) Collectors(java.util.stream.Collectors) FxPostInitialize(com.kyj.fx.voeditor.visual.framework.annotation.FxPostInitialize) MarginType(javafx.print.Printer.MarginType) List(java.util.List) Modifier(java.lang.reflect.Modifier) Scale(javafx.scene.transform.Scale) Optional(java.util.Optional) FontWeight(javafx.scene.text.FontWeight) AnimationUtils(jidefx.animation.AnimationUtils) Scene(javafx.scene.Scene) GargoyleBuilderFactory(com.kyj.fx.voeditor.visual.framework.builder.GargoyleBuilderFactory) WebEngine(javafx.scene.web.WebEngine) TextArea(javafx.scene.control.TextArea) MouseEvent(javafx.scene.input.MouseEvent) WebViewConsole(com.kyj.fx.voeditor.visual.component.console.WebViewConsole) Function(java.util.function.Function) TableColumn(javafx.scene.control.TableColumn) TableCell(javafx.scene.control.TableCell) Charset(java.nio.charset.Charset) State(javafx.concurrent.Worker.State) JavaTextView(com.kyj.fx.voeditor.visual.component.popup.JavaTextView) Callback(javafx.util.Callback) Tooltip(javafx.scene.control.Tooltip) GargoyleException(com.kyj.fx.voeditor.visual.exceptions.GargoyleException) FxMemory(com.kyj.fx.voeditor.visual.momory.FxMemory) PrinterJob(javafx.print.PrinterJob) OutputStream(java.io.OutputStream) KeyCode(javafx.scene.input.KeyCode) WebView(javafx.scene.web.WebView) Modality(javafx.stage.Modality) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) CloseableParent(com.kyj.fx.voeditor.visual.main.layout.CloseableParent) TablePosition(javafx.scene.control.TablePosition) WritableImage(javafx.scene.image.WritableImage) FileInputStream(java.io.FileInputStream) Consumer(java.util.function.Consumer) GargoyleSynchLoadBar(com.kyj.fx.voeditor.visual.component.bar.GargoyleSynchLoadBar) Stage(javafx.stage.Stage) Closeable(java.io.Closeable) SwingFXUtils(javafx.embed.swing.SwingFXUtils) Window(javafx.stage.Window) ChangeListener(javafx.beans.value.ChangeListener) InputStream(java.io.InputStream) SharedMemory(com.kyj.fx.voeditor.visual.momory.SharedMemory) Parent(javafx.scene.Parent) CloseableParent(com.kyj.fx.voeditor.visual.main.layout.CloseableParent) DockNode(com.kyj.fx.voeditor.visual.component.dock.pane.DockNode) Node(javafx.scene.Node) Method(java.lang.reflect.Method) GargoyleException(com.kyj.fx.voeditor.visual.exceptions.GargoyleException) FXMLLoader(javafx.fxml.FXMLLoader) URL(java.net.URL) IOException(java.io.IOException) GargoyleException(com.kyj.fx.voeditor.visual.exceptions.GargoyleException) MouseButton(javafx.scene.input.MouseButton) Button(javafx.scene.control.Button) FXMLController(com.kyj.fx.voeditor.visual.framework.annotation.FXMLController)

Aggregations

Consumer (java.util.function.Consumer)908 List (java.util.List)445 ArrayList (java.util.ArrayList)288 Test (org.junit.Test)250 Map (java.util.Map)228 IOException (java.io.IOException)223 Collectors (java.util.stream.Collectors)205 Collections (java.util.Collections)185 Arrays (java.util.Arrays)181 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)163 TimeUnit (java.util.concurrent.TimeUnit)157 HashMap (java.util.HashMap)152 Set (java.util.Set)149 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)146 Optional (java.util.Optional)132 Collection (java.util.Collection)127 Function (java.util.function.Function)119 CountDownLatch (java.util.concurrent.CountDownLatch)116 File (java.io.File)112 AtomicReference (java.util.concurrent.atomic.AtomicReference)111