Example usage for java.util.function Consumer accept

List of usage examples for java.util.function Consumer accept

Introduction

In this page you can find the example usage for java.util.function Consumer accept.

Prototype

void accept(T t);

Source Link

Document

Performs this operation on the given argument.

Usage

From source file:org.diorite.impl.world.WorldImpl.java

static void forChunksParallel(final int r, final ChunkPos center, final Consumer<ChunkPos> action) {
    if (r == 0) {
        action.accept(center);
        return;//w w  w  .j a v a2  s  .com
    }
    IntStream.rangeClosed(-r, r).parallel().forEach(x -> {
        if ((x == r) || (x == -r)) {
            IntStream.rangeClosed(-r, r).parallel().forEach(z -> action.accept(center.add(x, z)));
            return;
        }
        action.accept(center.add(x, r));
        action.accept(center.add(x, -r));
    });
}

From source file:org.netbeans.jcode.ng.main.AngularUtil.java

public static void copyDynamicFile(Consumer<FileTypeStream> parserManager, String inputResource,
        FileObject webRoot, Function<String, String> pathResolver, ProgressHandler handler) throws IOException {
    try {//from  w w  w.  j a v a 2  s .  c  o m
        InputStream inputStream = Angular1Generator.class.getClassLoader().getResourceAsStream(inputResource);
        String targetPath = pathResolver.apply(inputResource);
        if (targetPath == null) {
            return;
        }
        String fileType = inputResource.substring(inputResource.lastIndexOf('.') + 1);
        handler.progress(targetPath);
        FileObject target = org.openide.filesystems.FileUtil.createData(webRoot, targetPath);
        FileLock lock = target.lock();
        try (OutputStream outputStream = target.getOutputStream(lock)) {
            parserManager.accept(new FileTypeStream(fileType, inputStream, outputStream));
        } finally {
            lock.releaseLock();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        System.out.println("InputResource : " + inputResource);
    }
}

From source file:org.commonjava.indy.bind.jaxrs.util.ResponseUtils.java

public static Response formatResponseFromMetadata(final HttpExchangeMetadata metadata,
        final Consumer<ResponseBuilder> builderModifier) {
    int code = metadata.getResponseStatusCode();
    // 500-level error; use 502 response.
    Logger logger = LoggerFactory.getLogger(ResponseUtils.class);
    logger.info("Formatting response with code: {}", code);
    ResponseBuilder builder = null;/*  w  ww. j  a  v  a 2s. c  o  m*/
    if (code / 100 == 5) {
        builder = Response.status(502);
    }

    builder = Response.status(code);
    if (builderModifier != null) {
        builderModifier.accept(builder);
    }

    return builder.build();
}

From source file:org.commonjava.indy.folo.FoloUtils.java

/**
 * Read records from input stream and execute consumer function.
 * @param inputStream//from   ww  w. j  a v  a 2  s  .  c  o  m
 * @param consumer
 * @return count of records read from the stream
 */
public static int readZipInputStreamAnd(InputStream inputStream, Consumer<TrackedContent> consumer)
        throws IOException, ClassNotFoundException {
    int count = 0;
    try (ZipInputStream stream = new ZipInputStream(inputStream)) {
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            logger.trace("Read entry: %s, len: %d", entry.getName(), entry.getSize());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = stream.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }
            bos.close();

            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            TrackedContent record = (TrackedContent) ois.readObject();
            consumer.accept(record);
            count++;
        }
    }
    return count;
}

From source file:org.openecomp.sdc.be.components.impl.ImportUtils.java

public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) {
    Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
    if (fieldStringValue.isLeft()) {
        setter.accept(fieldStringValue.left().value());
    }/*from www  . j av a2s. c  o  m*/

}

From source file:org.elasticsearch.client.RequestTests.java

/**
 * Randomize the {@link FetchSourceContext} request parameters.
 *///from w  w w.  ja va  2 s.  c  o m
private static void randomizeFetchSourceContextParams(Consumer<FetchSourceContext> consumer,
        Map<String, String> expectedParams) {
    if (randomBoolean()) {
        if (randomBoolean()) {
            boolean fetchSource = randomBoolean();
            consumer.accept(new FetchSourceContext(fetchSource));
            if (fetchSource == false) {
                expectedParams.put("_source", "false");
            }
        } else {
            int numIncludes = randomIntBetween(0, 5);
            String[] includes = new String[numIncludes];
            StringBuilder includesParam = new StringBuilder();
            for (int i = 0; i < numIncludes; i++) {
                String include = randomAsciiOfLengthBetween(3, 10);
                includes[i] = include;
                includesParam.append(include);
                if (i < numIncludes - 1) {
                    includesParam.append(",");
                }
            }
            if (numIncludes > 0) {
                expectedParams.put("_source_include", includesParam.toString());
            }
            int numExcludes = randomIntBetween(0, 5);
            String[] excludes = new String[numExcludes];
            StringBuilder excludesParam = new StringBuilder();
            for (int i = 0; i < numExcludes; i++) {
                String exclude = randomAsciiOfLengthBetween(3, 10);
                excludes[i] = exclude;
                excludesParam.append(exclude);
                if (i < numExcludes - 1) {
                    excludesParam.append(",");
                }
            }
            if (numExcludes > 0) {
                expectedParams.put("_source_exclude", excludesParam.toString());
            }
            consumer.accept(new FetchSourceContext(true, includes, excludes));
        }
    }
}

From source file:gedi.util.FileUtils.java

public static void applyRecursively(String path, Consumer<File> action) {
    File root = new File(path);
    File[] list = root.listFiles();
    if (list == null)
        return;//from  w ww  .j  a  va2  s.c o m
    for (File f : list) {
        if (f.isDirectory())
            applyRecursively(f.getAbsolutePath(), action);
        else
            action.accept(f);
    }
}

From source file:com.opendoorlogistics.speedregions.excelshp.app.FileBrowserPanel.java

public static JTextField createTextField(String initialValue, final Consumer<String> filenameChangeListener) {
    final JTextField textField = new JTextField();
    if (initialValue != null) {
        textField.setText(initialValue);
    }// www . j a  v a 2 s  . co m

    if (filenameChangeListener != null) {
        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                fire();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                fire();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                fire();
            }

            private void fire() {
                filenameChangeListener.accept(textField.getText());
            }
        });
    }
    return textField;
}

From source file:org.commonjava.indy.bind.jaxrs.util.ResponseUtils.java

public static Response formatCreatedResponseWithJsonEntity(final URI location, final Object dto,
        final ObjectMapper objectMapper, final Consumer<ResponseBuilder> builderModifier) {
    ResponseBuilder builder = null;/*from ww w. j  av a2s.co  m*/
    if (dto == null) {
        builder = Response.noContent();
    } else {
        try {
            builder = Response.created(location).entity(objectMapper.writeValueAsString(dto))
                    .type(ApplicationContent.application_json);
        } catch (final JsonProcessingException e) {
            return formatResponse(e, "Failed to serialize DTO to JSON: " + dto, builderModifier);
        }
    }

    if (builderModifier != null) {
        builderModifier.accept(builder);
    }

    return builder.build();
}

From source file:fredboat.messaging.CentralMessaging.java

private static MessageFuture sendMessage0(@Nonnull MessageChannel channel, @Nonnull Message message,
        @Nullable Consumer<Message> onSuccess, @Nullable Consumer<Throwable> onFail) {
    if (channel == null) {
        throw new IllegalArgumentException("Channel is null");
    }/*from  w ww  .j  a  va 2 s .  c  o  m*/
    if (message == null) {
        throw new IllegalArgumentException("Message is null");
    }

    MessageFuture result = new MessageFuture();
    Consumer<Message> successWrapper = m -> {
        result.complete(m);
        Metrics.successfulRestActions.labels("sendMessage").inc();
        if (onSuccess != null) {
            onSuccess.accept(m);
        }
    };
    Consumer<Throwable> failureWrapper = t -> {
        result.completeExceptionally(t);
        if (onFail != null) {
            onFail.accept(t);
        } else {
            String info = String.format("Could not sent message\n%s\nto channel %s in guild %s",
                    message.getRawContent(), channel.getId(),
                    (channel instanceof TextChannel) ? ((TextChannel) channel).getGuild().getIdLong() : "null");
            getJdaRestActionFailureHandler(info).accept(t);
        }
    };

    try {
        channel.sendMessage(message).queue(successWrapper, failureWrapper);
    } catch (InsufficientPermissionException e) {
        failureWrapper.accept(e);
        if (e.getPermission() == Permission.MESSAGE_EMBED_LINKS) {
            handleInsufficientPermissionsException(channel, e);
        } else {
            //do not call CentralMessaging#handleInsufficientPermissionsException() from here as that will result in a loop
            log.warn("Could not send message to channel {} due to missing permission {}", channel.getIdLong(),
                    e.getPermission().getName(), e);
        }
    }
    return result;
}