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:Main.java

public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    numbers.forEach(new Consumer<Integer>() {
        @Override/*from   w  w w .  j  a  v a2s . c o m*/
        public void accept(Integer integer) {
            System.out.println(integer);
        }
    });

}

From source file:GoogleImages.java

public static void main(String[] args) throws InterruptedException {
    String searchTerm = "s woman"; // term to search for (use spaces to separate terms)
    int offset = 40; // we can only 20 results at a time - use this to offset and get more!
    String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet)
    String source = null; // string to save raw HTML source code

    // format spaces in URL to avoid problems
    searchTerm = searchTerm.replaceAll(" ", "%20");

    // get Google image search HTML source code; mostly built from PhyloWidget example:
    // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java
    int offset2 = 0;
    Set urlsss = new HashSet<String>();
    while (offset2 < 600) {
        try {/*from   www  . ja  va  2s.c  o m*/
            URL query = new URL("https://www.google.ru/search?start=" + offset2
                    + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A");
            HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection...
            urlc.setInstanceFollowRedirects(true);
            urlc.setRequestProperty("User-Agent", "");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file
            StringBuffer response = new StringBuffer();
            char[] buffer = new char[1024];
            while (true) {
                int charsRead = in.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                response.append(buffer, 0, charsRead);
            }
            in.close(); // close input stream (also closes network connection)
            source = response.toString();
        } // any problems connecting? let us know
        catch (Exception e) {
            e.printStackTrace();
        }

        // print full source code (for debugging)
        // println(source);
        // extract image URLs only, starting with 'imgurl'
        if (source != null) {
            //                System.out.println(source);
            int c = StringUtils.countMatches(source, "http://www.vmir.su");
            System.out.println(c);
            int index = source.indexOf("src=");
            System.out.println(source.subSequence(index, index + 200));
            while (index >= 0) {
                System.out.println(index);
                index = source.indexOf("src=", index + 1);
                if (index == -1) {
                    break;
                }
                String rr = source.substring(index,
                        index + 200 > source.length() ? source.length() : index + 200);

                if (rr.contains("\"")) {
                    rr = rr.substring(5, rr.indexOf("\"", 5));
                }
                System.out.println(rr);
                urlsss.add(rr);
            }
        }
        offset2 += 20;
        Thread.sleep(1000);
        System.out.println("off set = " + offset2);

    }

    System.out.println(urlsss);
    urlsss.forEach(new Consumer<String>() {

        public void accept(String s) {
            try {
                saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg");
            } catch (IOException ex) {
                Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    //            String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\"");

    // older regex, no longer working but left for posterity
    // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression
    // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))");    // (?i) means case-insensitive
    //            for (int i = 0; i < m.length; i++) {                                                          // iterate all results of the match
    //                println(i + ":\t" + m[i][1]);                                                         // print (or store them)**
    //            }
}

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

@Test
public void streamProcessesAllLines() 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(), 0L);
    console.stream(new Consumer<String>() {
        @Override/*from w w  w .  ja va2 s. c o  m*/
        public void accept(String s) {
            actual.add(s);
        }
    });
    assertArrayEquals(expected, actual.toArray());
    assertEquals(3L, console.totalLinesConsumed());
}

From source file:org.zalando.baigan.context.ConfigurationContextProviderRegistryImpl.java

@Override
public void register(@Nonnull final ContextProvider contextProvider) {
    Preconditions.checkNotNull(contextProvider, "Attempt to register null as a context provider!");
    contextProvider.getProvidedContexts().forEach(new Consumer<String>() {
        @Override/* w w  w  . j a va 2  s. co m*/
        public void accept(String context) {
            providerMap.put(context, contextProvider);
        }
    });

}

From source file:graphql.servlet.GraphQLVariables.java

public GraphQLVariables(GraphQLSchema schema, String query, Map<String, Object> variables) {
    super();//from   ww w . ja v a2  s.  com
    this.schema = schema;
    this.query = query;
    ObjectMapper objectMapper = new ObjectMapper();
    // this will help combating issues with unknown fields like clientMutationId
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    new Parser().parseDocument(query).getDefinitions().stream().filter(d -> d instanceof OperationDefinition)
            .map(d -> (OperationDefinition) d).flatMap(d -> d.getVariableDefinitions().stream())
            .forEach(new Consumer<VariableDefinition>() {
                @SneakyThrows
                @Override
                public void accept(VariableDefinition d) {
                    GraphQLType type;
                    Type t = d.getType();
                    if (t instanceof TypeName) {
                        type = schema.getType(((TypeName) t).getName());
                    } else if (t instanceof NonNullType) {
                        accept(new VariableDefinition(d.getName(), ((NonNullType) t).getType()));
                        return;
                    } else {
                        type = null;
                    }
                    if (type instanceof GraphQLObjectBackedByClass) {
                        String value = objectMapper.writeValueAsString(variables.get(d.getName()));
                        Object val = objectMapper.readValue(value,
                                ((GraphQLObjectBackedByClass) type).getObjectClass());
                        GraphQLVariables.this.put(d.getName(), val);
                    } else {
                        GraphQLVariables.this.put(d.getName(), variables.get(d.getName()));
                    }
                }
            });
}

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

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

    ConsoleStreamer console = new ConsoleStreamer(
            makeConsoleFile("first", "second", "third", "fourth").toPath(), 2L);
    console.stream(new Consumer<String>() {
        @Override//from ww  w. j  a v  a  2s . c  om
        public void accept(String s) {
            actual.add(s);
        }
    });
    assertArrayEquals(new String[] { "third", "fourth" }, actual.toArray());
    assertEquals(2L, console.totalLinesConsumed());

}

From source file:org.keycloak.testsuite.authorization.AttributeTest.java

@Test
public void testManageAttributes() throws ParseException {
    Map<String, Collection<String>> map = new HashedMap();

    map.put("integer", asList("1"));
    map.put("long", asList("" + Long.MAX_VALUE));
    map.put("string", asList("some string"));
    map.put("date", asList("12/12/2016"));
    map.put("ip_network_address", asList("127.0.0.1"));
    map.put("host_network_address", asList("localhost"));
    map.put("multi_valued", asList("1", "2", "3", "4"));

    Attributes attributes = Attributes.from(map);

    map.keySet().forEach(new Consumer<String>() {
        @Override//  w ww. ja v a 2  s .  c o m
        public void accept(String name) {
            assertTrue(attributes.exists(name));
        }
    });

    assertFalse(attributes.exists("not_found"));
    assertTrue(attributes.containsValue("integer", "1"));
    assertTrue(attributes.containsValue("multi_valued", "3"));

    assertEquals(1, attributes.getValue("multi_valued").asInt(0));
    assertEquals(4, attributes.getValue("multi_valued").asInt(3));

    assertEquals(new SimpleDateFormat("dd/MM/yyyy").parse("12/12/2016"),
            attributes.getValue("date").asDate(0, "dd/MM/yyyy"));

    assertEquals(InetAddress.getLoopbackAddress(), attributes.getValue("ip_network_address").asInetAddress(0));
    assertEquals(InetAddress.getLoopbackAddress(),
            attributes.getValue("host_network_address").asInetAddress(0));
}

From source file:com.github.jskarulis.dealsentry.HomeController.java

@RequestMapping(value = "/countries", method = RequestMethod.GET)
public List<Country> findAll() {
    final List<Country> countryList = new ArrayList<>();
    final Iterable<Country> countries = countryRepository.findAll();
    countries.forEach(new Consumer<Country>() {
        @Override/*  ww  w  . j  a  va  2 s .c  o  m*/
        public void accept(Country country) {
            countryList.add(country);
        }
    });
    return countryList;
}

From source file:jease.cms.service.Properties.java

/**
 * Returns all paths for properties which can act as item providers for
 * selectable properties.//from  ww  w  . j av  a  2 s . c  om
 */
public List<String> getProviderPaths() {
    final List<String> result = new ArrayList<>();
    nodeService.traverse(nodes.getRoot(), new Consumer<Node>() {
        public void accept(Node node) {
            Content content = (Content) node;
            if (content.getProperties() != null) {
                for (Property property : content.getProperties()) {
                    if (property instanceof Provider) {
                        result.add(getPath(content, property));
                    }
                }
            }
        }
    });
    return result;
}

From source file:com.thoughtworks.go.plugin.infra.service.DefaultPluginLoggingServiceTest.java

private void assertPluginLogFile(String pluginId, String expectedPluginLogFileName) {
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

    DefaultPluginLoggingService loggingService = new DefaultPluginLoggingService(systemEnvironment);
    loggingService.debug(pluginId, "some-logger-name", "message");

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger("plugin." + pluginId);
    ArrayList<Appender<ILoggingEvent>> appenders = new ArrayList<>();
    logger.iteratorForAppenders().forEachRemaining(new Consumer<Appender<ILoggingEvent>>() {
        @Override//from w  w w . ja  v a2  s . c  o m
        public void accept(Appender<ILoggingEvent> iLoggingEventAppender) {
            appenders.add(iLoggingEventAppender);
        }
    });

    String loggingDirectory = loggingService.getCurrentLogDirectory();
    assertThat(appenders.size(), is(1));
    assertThat(new File(((FileAppender) appenders.get(0)).rawFileProperty()),
            is(new File(loggingDirectory, expectedPluginLogFileName)));
}