Example usage for java.util.function Consumer Consumer

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

Introduction

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

Prototype

Consumer

Source Link

Usage

From source file:com.thoughtworks.go.domain.ConsoleStreamerTest.java

@Test
public void streamAssumesNegativeStartLineIsZero() throws Exception {
    String[] expected = new String[] { "First line", "Second line", "Third line" };
    final ArrayList<String> actual = new ArrayList<>();

    ConsoleStreamer console = new ConsoleStreamer(makeConsoleFile(expected).toPath(), -1L);
    console.stream(new Consumer<String>() {
        @Override//from   w w w.  j av a  2 s  . co m
        public void accept(String s) {
            actual.add(s);
        }
    });
    assertArrayEquals(expected, actual.toArray());
    assertEquals(3L, console.totalLinesConsumed());
}

From source file:dk.dma.ais.tracker.ScenarioTracker.java

@Override
public Subscription readFromStream(AisPacketStream stream) {
    return stream.subscribe(new Consumer<AisPacket>() {
        public void accept(AisPacket p) {
            update(p);//from   w  w  w.j  a  v a 2  s  .  c o  m
        }
    });
}

From source file:com.microsoft.azure.utility.compute.TestCleanupTask.java

private void removeRGs(ArrayList<ResourceGroupExtended> groups) {
    groups.stream().filter(new Predicate<ResourceGroupExtended>() {
        @Override//from   www. j a  v  a 2 s .co  m
        public boolean test(ResourceGroupExtended rg) {
            return rg.getName().startsWith("javatest");
        }
    }).forEach(new Consumer<ResourceGroupExtended>() {
        @Override
        public void accept(ResourceGroupExtended rg) {
            try {
                resourceManagementClient.getResourceGroupsOperations().beginDeleting(rg.getName());
                log.info("removed rg: " + rg.getName());
            } catch (Exception e) {
                log.info(e.toString());
            }
        }
    });
}

From source file:dk.dma.ais.tracker.ScenarioTracker.java

public void readFromPacketReader(AisPacketReader packetReader) throws IOException {
    packetReader.forEachRemaining(new Consumer<AisPacket>() {
        @Override/*from   w  w w. j a  v a2 s  .co m*/
        public void accept(AisPacket p) {
            update(p);
        }
    });
}

From source file:com.qwazr.compiler.JavaCompiler.java

private JavaCompiler(ExecutorService executorService, File javaSourceDirectory, File javaClassesDirectory,
        String classPath, Collection<URL> urlList) throws IOException {
    this.classPath = classPath;
    this.javaSourceDirectory = javaSourceDirectory;
    String javaSourcePrefix = javaSourceDirectory.getAbsolutePath();
    javaSourcePrefixSize = javaSourcePrefix.endsWith("/") ? javaSourcePrefix.length()
            : javaSourcePrefix.length() + 1;
    this.javaClassesDirectory = javaClassesDirectory;
    if (this.javaClassesDirectory != null && !this.javaClassesDirectory.exists())
        this.javaClassesDirectory.mkdir();
    compilerLock = new LockUtils.ReadWriteLock();
    compileDirectory(javaSourceDirectory);
    directorWatcher = DirectoryWatcher.register(javaSourceDirectory.toPath(), new Consumer<Path>() {
        @Override/*  w  w w .j  a v  a2  s  . com*/
        public void accept(Path path) {
            try {
                compileDirectory(path.toFile());
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    });
    executorService.execute(directorWatcher);
}

From source file:com.yqboots.web.thymeleaf.processor.element.AlertElementProcessor.java

/**
 * {@inheritDoc}//w w  w.  j a  va  2s .  com
 */
@Override
protected List<Node> getMarkupSubstitutes(final Arguments arguments, final Element element) {
    final List<Node> nodes = new ArrayList<>();

    final String levelAttrValue = StringUtils.defaultIfBlank(element.getAttributeValue(ATTR_LEVEL),
            DEFAULT_LEVEL);

    final VariablesMap<String, Object> variables = arguments.getContext().getVariables();
    variables.values().stream().filter(new Predicate<Object>() {
        @Override
        public boolean test(final Object o) {
            return BindingResult.class.isAssignableFrom(o.getClass());
        }
    }).forEach(new Consumer<Object>() {
        @Override
        public void accept(final Object value) {
            BindingResult bindingResult = (BindingResult) value;
            if (bindingResult.hasGlobalErrors()) {
                nodes.add(build(arguments, bindingResult.getGlobalErrors(), levelAttrValue));
            }
        }
    });

    return nodes;
}

From source file:com.thoughtworks.go.domain.ConsoleStreamerTest.java

@Test
public void processesNothingWhenStartLineIsBeyondEOF() throws Exception {
    final ArrayList<String> actual = new ArrayList<>();

    ConsoleStreamer console = new ConsoleStreamer(makeConsoleFile("first", "second").toPath(), 5L);
    console.stream(new Consumer<String>() {
        @Override//from  ww w .j av  a 2 s  .c  o  m
        public void accept(String s) {
            actual.add(s);
        }
    });
    assertTrue(actual.isEmpty());
    assertEquals(0L, console.totalLinesConsumed());
}

From source file:org.rapid.develop.baidu.plugin.BaiduUtil.java

public static void runMapReduce(String accessKey, String secretKey, RunMapReduce mapReduce) {

    BceClientConfiguration config = new BceClientConfiguration();
    config.setCredentials(new DefaultBceCredentials(accessKey, secretKey));
    BmrClient client = new BmrClient(config);

    Master master = mapReduce.getMaster();
    final ModelSet<Slave> slaves = mapReduce.getSlaves();
    ModelSet<org.rapid.develop.baidu.plugin.mapreduce.model.Step> steps = mapReduce.getSteps();
    Pig pig = mapReduce.getPig();/*  w ww  .  j  a va 2s.co  m*/
    HBase hbase = mapReduce.getHbase();
    Hive hive = mapReduce.getHive();

    String clusterId = null;
    try {
        final CreateClusterRequest request = new CreateClusterRequest().withName(mapReduce.getName())
                .withImageType(mapReduce.getImageType()).withImageVersion(mapReduce.getImageVersion())
                .withAutoTerminate(mapReduce.getAutoTerminate()).withLogUri(mapReduce.getLogUri())
                .withInstanceGroup(new InstanceGroupConfig().withName("ig-master").withType("Master")
                        .withInstanceType(master.getInstanceType())
                        .withInstanceCount(master.getInstanceCount()));

        slaves.forEach(new Consumer<Slave>() {
            @Override
            public void accept(Slave slave) {
                request.withInstanceGroup(new InstanceGroupConfig().withName("ig-core").withType("Core")
                        .withInstanceType(slave.getInstanceType()).withInstanceCount(slave.getInstanceCount()));
            }
        });

        steps.forEach(new Consumer<org.rapid.develop.baidu.plugin.mapreduce.model.Step>() {
            @Override
            public void accept(org.rapid.develop.baidu.plugin.mapreduce.model.Step step) {
                if (step.getType().equals("pig")) {
                    request.withStep(new PigStepConfig().withName(step.getName())
                            .withActionOnFailure(step.getActionOnFailure()).withScript(step.getJar())
                            .withArguments(step.getArguments()));
                } else if (step.getType().equals("hive")) {
                    request.withStep(new HiveStepConfig().withName(step.getName())
                            .withActionOnFailure(step.getActionOnFailure()).withScript(step.getJar())
                            .withArguments(step.getArguments()));
                } else {
                    request.withStep(new JavaStepConfig().withName(step.getName())
                            .withActionOnFailure(step.getActionOnFailure()).withJar(step.getJar())
                            .withMainClass(step.getMainClass()).withArguments(step.getArguments()));
                }
            }
        });

        if (StringUtils.isNotEmpty(pig.getVersion())) {
            request.withApplication(new PigApplicationConfig().withVersion(pig.getVersion()));
        }
        if (StringUtils.isNotEmpty(hive.getVersion())) {
            request.withApplication(new HiveApplicationConfig().withVersion(hive.getVersion())
                    .withMetastore(hive.getMetastore()));
        }
        if (StringUtils.isNotEmpty(hbase.getVersion())) {
            request.withApplication(new HBaseApplicationConfig().withVersion(hbase.getVersion())
                    .withBackupEnabled(hbase.getBackbupEnabled()).withBackupLocation(hbase.getBackupLocation())
                    .withBackupIntervalInMinutes(hbase.getBackupIntervalInMinutes())
                    .withBackupStartDatetime(hbase.getBackupStartDatetime()));
        }

        CreateClusterResponse response = client.createCluster(request);
        clusterId = response.getClusterId();
    } catch (BceServiceException e) {
        System.out.println("Create cluster failed: " + e.getErrorMessage());
    } catch (BceClientException e) {
        System.out.println(e.getMessage());
    }
}

From source file:org.jnario.doc.AbstractDocGenerator.java

public void doGenerate(final Resource input, final IFileSystemAccess fsa,
        final Executable2ResultMapping spec2ResultMapping) {
    this.initResultMapping(spec2ResultMapping);
    final Consumer<JnarioFile> _function = new Consumer<JnarioFile>() {
        @Override/* w  w  w.j ava 2 s  . c  o m*/
        public void accept(final JnarioFile it) {
            final Consumer<JnarioClass> _function = new Consumer<JnarioClass>() {
                @Override
                public void accept(final JnarioClass it) {
                    AbstractDocGenerator.this._htmlFileBuilder.generate(it, fsa,
                            AbstractDocGenerator.this.createHtmlFile(it));
                }
            };
            Iterables.<JnarioClass>filter(it.getXtendTypes(), JnarioClass.class).forEach(_function);
        }
    };
    Iterables.<JnarioFile>filter(input.getContents(), JnarioFile.class).forEach(_function);
}

From source file:dk.dma.vessel.track.store.AisStoreClient.java

public List<PastTrackPos> getPastTrack(int mmsi, Integer minDist, Duration age) {

    // Determine URL
    age = age != null ? age : Duration.parse(pastTrackTtl);
    minDist = minDist == null ? Integer.valueOf(pastTrackMinDist) : minDist;
    ZonedDateTime now = ZonedDateTime.now();
    String from = now.format(DateTimeFormatter.ISO_INSTANT);
    ZonedDateTime end = now.minus(age);
    String to = end.format(DateTimeFormatter.ISO_INSTANT);
    String interval = String.format("%s/%s", to, from);
    String url = String.format("%s?mmsi=%d&interval=%s", aisViewUrl, mmsi, interval);

    final List<PastTrackPos> track = new ArrayList<>();
    try {/*  ww w  . j  a va  2s  . c o m*/
        long t0 = System.currentTimeMillis();

        // TEST
        url = url + "&filter=" + URLEncoder.encode("(s.country not in (GBR)) & (s.region!=808)", "UTF-8");

        // Set up a few timeouts and fetch the attachment
        URLConnection con = new URL(url).openConnection();
        con.setConnectTimeout(10 * 1000); // 10 seconds
        con.setReadTimeout(60 * 1000); // 1 minute

        if (!StringUtils.isEmpty(aisAuthHeader)) {
            con.setRequestProperty("Authorization", aisAuthHeader);
        }

        try (InputStream in = con.getInputStream(); BufferedInputStream bin = new BufferedInputStream(in)) {
            AisReader aisReader = AisReaders.createReaderFromInputStream(bin);
            aisReader.registerPacketHandler(new Consumer<AisPacket>() {
                @Override
                public void accept(AisPacket p) {
                    AisMessage message = p.tryGetAisMessage();
                    if (message == null || !(message instanceof IVesselPositionMessage)) {
                        return;
                    }
                    VesselTarget target = new VesselTarget();
                    target.merge(p, message);
                    if (!target.checkValidPos()) {
                        return;
                    }
                    track.add(new PastTrackPos(target.getLat(), target.getLon(), target.getCog(),
                            target.getSog(), target.getLastPosReport()));
                }
            });
            aisReader.start();
            try {
                aisReader.join();
            } catch (InterruptedException e) {
                return null;
            }
        }
        LOG.info(String.format("Read %d past track positions in %d ms", track.size(),
                System.currentTimeMillis() - t0));
    } catch (IOException e) {
        LOG.error("Failed to make REST query: " + url);
        throw new InternalError("REST endpoint failed");
    }
    LOG.info("AisStore returned track with " + track.size() + " points");
    return PastTrack.downSample(track, minDist, age.toMillis());
}