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:dk.dbc.rawrepo.oai.OAIWorker.java

/**
 * Get a request parameter/*from   w  w  w.jav a 2s.c  o  m*/
 *
 * @param name   name of the parameter
 * @param action what to do with the parameter (null is ok)
 * @return content of parameter
 */
private String getParameter(String name, Consumer<String> action) {
    String value = params.getFirst(name);
    if (value != null && action != null) {
        action.accept(value);
    }
    return value;

}

From source file:com.thoughtworks.go.api.base.JsonOutputWriter.java

private void bufferWriterAndFlushWhenDone(Writer writer, Consumer<BufferedWriter> consumer) {
    BufferedWriter bufferedWriter = (writer instanceof BufferedWriter) ? (BufferedWriter) writer
            : new BufferedWriter(writer, 32 * 1024);
    try {//ww w.j  av  a  2 s.c  o  m
        try {
            consumer.accept(bufferedWriter);
        } finally {
            bufferedWriter.flush();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kie.appformer.flow.unit.FlowDescriptorConverterTest.java

@Test
public void flowWithUIComponentAndCombinedShowAndHide() throws Exception {
    final SimpleType string = typeFactory.simpleType(String.class);
    final SimpleType object = typeFactory.simpleType(Object.class);
    final UIComponentDescriptor componentDescriptor = descriptorFactory
            .createUIComponentDescriptor("StringEditor", string, string, object);
    final Object viewObj = new Object();
    final UIComponent<String, String, Object> component = new UIComponent<String, String, Object>() {

        @Override//from   w w  w . java  2s  .c om
        public void start(final String input, final Consumer<String> callback) {
            final String reversed = StringUtils.reverse(input);
            callback.accept(reversed);
        }

        @Override
        public void onHide() {
        }

        @Override
        public Object asComponent() {
            return viewObj;
        }

        @Override
        public String getName() {
            return "StringEditor";
        }
    };
    final List<CapturedAction> capturedActions = new ArrayList<>();
    final DisplayerDescriptor displayerDescriptor = descriptorFactory.createDisplayerDescriptor("TestDisplayer",
            object);
    registry.addDisplayer(displayerDescriptor, () -> new Displayer<Object>() {

        @Override
        public void show(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.SHOW, component));
        }

        @Override
        public void hide(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.HIDE, component));
        }
    });

    registry.addUIComponent(componentDescriptor, () -> component);
    final UIStepDescriptor uiStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.SHOW_AND_HIDE, componentDescriptor);
    final AppFlowDescriptor uiFlow = descriptorFactory.createAppFlowDescriptor(uiStepDescriptor);

    try {
        @SuppressWarnings("unchecked")
        final AppFlow<String, String> flow = (AppFlow<String, String>) converter.convert(registry, uiFlow);
        final Ref<String> retVal = new Ref<>();
        executor.execute("foo", flow, val -> retVal.val = val);
        assertNotNull(retVal.val);
        assertEquals("oof", retVal.val);
        assertEquals(Arrays.asList(new CapturedAction(UIStepDescriptor.Action.SHOW, component),
                new CapturedAction(UIStepDescriptor.Action.HIDE, component)), capturedActions);
    } catch (final AssertionError ae) {
        throw ae;
    } catch (final Throwable t) {
        throw new AssertionError(t);
    }
}

From source file:org.kie.appformer.flow.unit.FlowDescriptorConverterTest.java

@Test
public void flowWithUIComponentAndSeparateShowAndHide() throws Exception {
    final SimpleType string = typeFactory.simpleType(String.class);
    final SimpleType object = typeFactory.simpleType(Object.class);
    final UIComponentDescriptor componentDescriptor = descriptorFactory
            .createUIComponentDescriptor("StringEditor", string, string, object);
    final Object viewObj = new Object();
    final UIComponent<String, String, Object> component = new UIComponent<String, String, Object>() {

        @Override/*w  w  w.  j  a  v  a 2s .  co m*/
        public void start(final String input, final Consumer<String> callback) {
            final String reversed = StringUtils.reverse(input);
            callback.accept(reversed);
        }

        @Override
        public void onHide() {
        }

        @Override
        public Object asComponent() {
            return viewObj;
        }

        @Override
        public String getName() {
            return "StringEditor";
        }
    };
    final List<CapturedAction> capturedActions = new ArrayList<>();
    final DisplayerDescriptor displayerDescriptor = descriptorFactory.createDisplayerDescriptor("TestDisplayer",
            object);
    registry.addDisplayer(displayerDescriptor, () -> new Displayer<Object>() {

        @Override
        public void show(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.SHOW, component));
        }

        @Override
        public void hide(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.HIDE, component));
        }
    });

    registry.addUIComponent(componentDescriptor, () -> component);
    final UIStepDescriptor showStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.SHOW, componentDescriptor);
    final UIStepDescriptor hideStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.HIDE, componentDescriptor);
    final TransformationDescriptor doubleStringDescriptor = descriptorFactory
            .createTransformationDescriptor("DoubleString", string, string);
    registry.addTransformation(doubleStringDescriptor, () -> (final String s) -> s + s);

    final AppFlowDescriptor uiFlow = descriptorFactory.createAppFlowDescriptor(showStepDescriptor)
            .andThen(doubleStringDescriptor).andThen(hideStepDescriptor);

    try {
        @SuppressWarnings("unchecked")
        final AppFlow<String, String> flow = (AppFlow<String, String>) converter.convert(registry, uiFlow);
        final Ref<String> retVal = new Ref<>();
        executor.execute("foo", flow, val -> retVal.val = val);
        assertNotNull(retVal.val);
        assertEquals("oofoof", retVal.val);
        assertEquals(Arrays.asList(new CapturedAction(UIStepDescriptor.Action.SHOW, component),
                new CapturedAction(UIStepDescriptor.Action.HIDE, component)), capturedActions);
    } catch (final AssertionError ae) {
        throw ae;
    } catch (final Throwable t) {
        throw new AssertionError(t);
    }
}

From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java

/** Logic to perform the custom deduplication with the current and new versions
 * @param maybe_custom_handler/*from www.  java 2  s . co  m*/
 * @param new_record
 * @param old_record
 * @returns list of Json objects to delete
 */
protected static Stream<JsonNode> handleCustomDeduplication(
        Optional<Tuple2<IEnrichmentBatchModule, DeduplicationEnrichmentContext>> maybe_custom_handler,
        final List<Tuple3<Long, IBatchRecord, ObjectNode>> new_records, final Collection<JsonNode> old_records,
        final JsonNode key) {
    return maybe_custom_handler.map(handler_context -> {
        handler_context._2().resetMutableState(old_records, key);

        final Consumer<IEnrichmentBatchModule> handler = new_module -> {
            final Stream<Tuple2<Long, IBatchRecord>> dedup_stream = Stream.concat(
                    new_records.stream().map(t3 -> Tuples._2T(t3._1(), t3._2())),
                    old_records.stream().map(old_record -> Tuples._2T(-1L,
                            (IBatchRecord) (new BatchRecordUtils.InjectedJsonBatchRecord(old_record)))));

            final int batch_size = new_records.size();

            new_module.onObjectBatch(dedup_stream, Optional.of(batch_size).filter(__ -> !old_records.isEmpty()), // (ie leave batch size blank if there's no dedup) 
                    Optional.of(key));

            new_module.onStageComplete(false);
        };

        handler.accept(handler_context._1());

        return handler_context._2().getObjectIdsToDelete();
    }).orElse(Stream.empty());
}

From source file:org.briljantframework.array.AbstractBaseArray.java

@Override
public void forEach(int dim, Consumer<E> consumer) {
    int size = vectors(dim);
    for (int i = 0; i < size; i++) {
        consumer.accept(getVector(dim, i));
    }/*from   w w w  .  java  2  s. co m*/
}

From source file:org.kie.workbench.common.forms.migration.tool.pipelines.basic.AbstractFormDefinitionGeneratorTest.java

protected void initForm(Consumer<Form> formConsumer, String resourcePath, String name, Path formPath)
        throws Exception {
    Form form = serializer.loadFormFromXML(
            IOUtils.toString(new InputStreamReader(this.getClass().getResourceAsStream(resourcePath + name))));
    formConsumer.accept(form);
    when(formPath.toURI()).thenReturn(ROOT_PATH + name);
    when(formPath.getFileName()).thenReturn(name);
}

From source file:org.jboss.pnc.buildagent.client.BuildAgentClient.java

public BuildAgentClient(String termBaseUrl, Optional<Consumer<String>> responseDataConsumer,
        Consumer<TaskStatusUpdateEvent> onStatusUpdate, String commandContext, ResponseMode responseMode,
        boolean readOnly) throws TimeoutException, InterruptedException {

    this.responseMode = responseMode;
    this.readOnly = readOnly;

    Consumer<TaskStatusUpdateEvent> onStatusUpdateInternal = (event) -> {
        onStatusUpdate.accept(event);
    };//w  ww .ja  va 2s  . co m

    statusUpdatesClient = connectStatusListenerClient(termBaseUrl, onStatusUpdateInternal, commandContext);
    commandExecutingClient = connectCommandExecutingClient(termBaseUrl, responseDataConsumer, commandContext);
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

public void unsignJAR(Path sourceJARFile, Path targetJARFile, Consumer<String> observer)
        throws CommandExecutionException {

    if (logger.isDebugEnabled()) {
        logger.debug("[UNSIGN] sourceJARFilePath={}, targetJARFilePath={}", sourceJARFile, targetJARFile);
    }//w w  w  . j  a  v  a  2 s  .  c  om

    //
    // Verify source jar
    //
    File sourceJarFile = verifySource(sourceJARFile);
    observer.accept("Verifying source JAR '" + sourceJarFile.getName() + "'");

    if (logger.isDebugEnabled()) {
        logger.debug("[UNSIGN] source jar file name={}", sourceJarFile.getName());
    }

    //
    // Create a temporary and unique folder
    //
    observer.accept("Creating temp dir");
    Path appDir = createTempDir();

    Preconditions.checkNotNull(tempDir);

    //
    // Register cleanup handler
    //
    observer.accept("Registering cleanup handler");
    registerCleanup();

    //
    // Copy jarFile to temp folder
    //
    observer.accept("Copying JAR '" + sourceJarFile.getName() + "'");
    Path workingJarFile = copyJAR(sourceJarFile);

    //
    // Unpack JAR
    //
    unJAR(workingJarFile.toString(), tempDir);
    observer.accept("Unpacking JAR '" + workingJarFile.toString() + "'");
    observer.accept("Deleting working JAR file");
    workingJarFile.toFile().delete(); // don't include for later re-jar operation

    //
    // Locate .SF files. Remove these and corresponding signature blocks like .RSA.
    //
    observer.accept("Removing old signature blocks");
    File metaInfDir = new File(tempDir.toFile(), "META-INF");
    removeSigs(metaInfDir);

    //
    // Strip the SHA.*\: entries from the MANIFEST.MF (ok to leave Name: lines?)
    //
    observer.accept("Editing MANIFEST.MF");
    editManifest(metaInfDir);

    //
    // Repack JAR
    //
    observer.accept("Repacking JAR '" + targetJARFile.toString() + "'");
    repackJAR(targetJARFile, appDir);
}

From source file:org.commonjava.indy.pkg.npm.jaxrs.NPMContentAccessHandler.java

private Response responseWithBuilder(final Response.ResponseBuilder builder,
        final Consumer<Response.ResponseBuilder> builderModifier) {
    if (builderModifier != null) {
        builderModifier.accept(builder);
    }/*www.  j a  va 2  s. co m*/
    return builder.build();
}