Example usage for java.util Arrays stream

List of usage examples for java.util Arrays stream

Introduction

In this page you can find the example usage for java.util Arrays stream.

Prototype

public static DoubleStream stream(double[] array) 

Source Link

Document

Returns a sequential DoubleStream with the specified array as its source.

Usage

From source file:com.github.rutledgepaulv.qbuilders.visitors.PredicateVisitor.java

protected boolean regex(Object actual, Object query) {
    Predicate<String> test;

    if (query instanceof String) {
        String queryRegex = (String) query;
        test = Pattern.compile(queryRegex).asPredicate();
    } else {/*from  ww  w.j  a  v a2 s . c  o  m*/
        return false;
    }

    if (actual.getClass().isArray()) {
        String[] values = (String[]) actual;
        return Arrays.stream(values).anyMatch(test);
    } else if (Collection.class.isAssignableFrom(actual.getClass())) {
        Collection<String> values = (Collection<String>) actual;
        return values.stream().anyMatch(test);
    } else if (actual instanceof String) {
        return test.test((String) actual);
    }

    return false;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings.java

private Field getServiceField(String name) {
    String reducedName = name.replace("-", "").replace("_", "");

    Optional<Field> matchingField = Arrays.stream(Services.class.getDeclaredFields())
            .filter(f -> f.getName().equalsIgnoreCase(reducedName)).findFirst();

    return matchingField
            .orElseThrow(() -> new HalException(Problem.Severity.FATAL, "Unknown service " + reducedName));
}

From source file:Main.java

public static List<Component> getAllComponentsFrom(final Component component, List<Component> components) {
    if (component instanceof Container) {
        Arrays.stream(getComponents(Container.class.cast(component)))
                .forEach(component0 -> getAllComponentsFrom(component0, components));
    }//from  ww  w  .  j  a  va2  s .  c om

    return components;
}

From source file:ninja.eivind.hotsreplayuploader.utils.StormHandler.java

/**
 * Retrieves a {@link List} of {@link File}s, each containing files for a specific {@link Account}.
 * @return {@link List} of directories or an empty {@link List}
 *///from  w w w  . ja v  a2 s .  c o m
private List<File> getAccountDirectories() {
    final List<File> hotsAccounts = new ArrayList<>();
    File[] files = getHotSHome().listFiles((dir, name) -> name.matches(ACCOUNT_FOLDER_FILTER));
    if (files == null) {
        files = new File[0];
    }
    for (final File file : files) {
        final File[] hotsFolders = file.listFiles((dir, name) -> name.matches(hotsAccountFilter));
        Arrays.stream(hotsFolders).forEach(hotsAccounts::add);
    }

    return hotsAccounts.stream().sorted((f1, f2) -> Long.compare(maxLastModified(f2), maxLastModified(f1)))
            .collect(Collectors.toList());
}

From source file:com.github.ljtfreitas.restify.http.client.request.apache.httpclient.ApacheHttpClientRequest.java

private ApacheHttpClientResponse responseOf(HttpResponse httpResponse) throws IOException {
    StatusCode statusCode = StatusCode.of(httpResponse.getStatusLine().getStatusCode());

    Headers headers = new Headers();
    Arrays.stream(httpResponse.getAllHeaders()).forEach(
            h -> headers.add(new com.github.ljtfreitas.restify.http.client.Header(h.getName(), h.getValue())));

    HttpEntity entity = httpResponse.getEntity();

    InputStream stream = entity != null ? entity.getContent() : new ByteArrayInputStream(new byte[0]);

    return new ApacheHttpClientResponse(statusCode, headers, stream, entity, httpResponse, this);
}

From source file:com.linecorp.bot.spring.boot.support.LineMessageHandlerSupport.java

@VisibleForTesting
void refresh() {/*w ww. j  a  v a  2s.  c o m*/
    final Map<String, Object> handlerBeanMap = applicationContext
            .getBeansWithAnnotation(LineMessageHandler.class);

    final List<HandlerMethod> collect = handlerBeanMap.values().stream().flatMap((Object bean) -> {
        final Method[] uniqueDeclaredMethods = ReflectionUtils.getUniqueDeclaredMethods(bean.getClass());

        return Arrays.stream(uniqueDeclaredMethods).map(method -> getMethodHandlerMethodFunction(bean, method))
                .filter(Objects::nonNull);
    }).sorted(HANDLER_METHOD_PRIORITY_COMPARATOR).collect(Collectors.toList());

    log.info("Registered LINE Messaging API event handler: count = {}", collect.size());
    collect.forEach(item -> log.info("Mapped \"{}\" onto {}", item.getSupportType(),
            item.getHandler().toGenericString()));

    eventConsumerList = collect;
}

From source file:natalia.dymnikova.cluster.scheduler.impl.RolesChecker.java

private boolean doCheck(final Set<String> roles, final Class<? extends Remote> aClass) {
    final Field[] declaredFields = aClass.getDeclaredFields();
    final List<TypeFilter> fields = Arrays.stream(declaredFields)
            .filter(field -> field.isAnnotationPresent(Autowired.class))
            // TODO deal with 3pp dependencies
            .filter(field -> field.getType().getPackage().getName().startsWith(basePackage)).map(Field::getType)
            .map(AssignableTypeFilter::new).collect(toList());

    final MultiValueMap<String, Object> matchAll = new LinkedMultiValueMap<>();
    matchAll.put("value", singletonList(roles.toArray(new String[roles.size()])));

    final List<Set<ScannedGenericBeanDefinition>> set = scan(basePackage, fields);

    return set.stream().map(definitions -> definitions.stream().map(def -> {
        final MultiValueMap<String, Object> map = ofNullable(
                def.getMetadata().getAllAnnotationAttributes(Profile.class.getName())).orElse(matchAll);

        //noinspection unchecked
        return ((List<String[]>) (Object) map.get("value")).stream().flatMap(Arrays::stream).collect(toList());
    }).flatMap(Collection::stream).collect(toList()))
            .allMatch(profiles -> profiles.stream().filter(roles::contains).findAny().isPresent());
}

From source file:com.thorpora.module.core.error.ErrorLogger.java

private void map(Level logLevel, boolean printStackTrace, Class... exceptionClasses) {
    Arrays.stream(exceptionClasses).forEach(c -> {
        levelMapping.put(c, logLevel);/*from  w ww.  j  a v  a  2s . c  o m*/
        stackMapping.put(c, printStackTrace);
    });
}

From source file:com.ikanow.aleph2.analytics.hadoop.assets.BeFileInputFormat.java

@Override
public List<InputSplit> getSplits(JobContext context) throws IOException {
    logger.debug("BeFileInputFormat.getSplits");

    super.setMaxSplitSize(MAX_SPLIT_SIZE);

    try {//from  w  w w  .  j av a 2  s.  c  o m
        final List<InputSplit> splits = Lambdas.get(Lambdas.wrap_u(() -> {
            final List<InputSplit> tmp = super.getSplits(context);

            String debug_max_str = context.getConfiguration().get(BatchEnrichmentJob.BE_DEBUG_MAX_SIZE);
            if (null != debug_max_str) {
                final int requested_records = Integer.parseInt(debug_max_str);

                // dump 5* the request number of splits into one mega split
                // to strike a balance between limiting the data and making sure for 
                // tests that enough records are generated

                final CombineFileSplit combined = new CombineFileSplit(
                        tmp.stream().map(split -> (CombineFileSplit) split)
                                .flatMap(split -> Arrays.stream(split.getPaths())).limit(5L * requested_records)
                                .<Path>toArray(size -> new Path[size]),
                        ArrayUtils.toPrimitive(
                                tmp.stream().map(split -> (CombineFileSplit) split)
                                        .flatMap(split -> Arrays.stream(split.getStartOffsets()).boxed())
                                        .limit(5L * requested_records).<Long>toArray(size -> new Long[size]),
                                0L),
                        ArrayUtils.toPrimitive(
                                tmp.stream().map(split -> (CombineFileSplit) split)
                                        .flatMap(split -> Arrays.stream(split.getLengths()).boxed())
                                        .limit(5L * requested_records).<Long>toArray(size -> new Long[size]),
                                0L),
                        tmp.stream().map(split -> (CombineFileSplit) split)
                                .flatMap(Lambdas.wrap_u(split -> Arrays.stream(split.getLocations())))
                                .limit(5L * requested_records).<String>toArray(size -> new String[size]));
                return Arrays.<InputSplit>asList(combined);
            } else
                return tmp;
        }));

        logger.debug("BeFileInputFormat.getSplits: " + ((splits != null) ? splits.size() : "null"));
        return splits;

    } catch (Throwable t) {
        logger.error(t);
        throw new IOException(t);
    }
}

From source file:de.arraying.arraybot.manager.ScriptManager.java

/**
 * Executes the script./* w  w w.j  a  v  a 2 s.c o m*/
 * @param scriptUrl The script URL.
 * @param environment The command environment.
 * @param error The error consumer.
 * @throws IOException If an exception occurs parsing the code.
 */
public void executeScript(String scriptUrl, CommandEnvironment environment, Consumer<Exception> error)
        throws Exception {
    PrimeSourceProvider provider = Prime.Util.getProvider(PRIME_TEST, scriptUrl);
    if (provider == null || provider instanceof StandardProvider) {
        invalidURL(environment.getChannel());
        return;
    }
    String code;
    try {
        code = IOUtils.toString(new URL(scriptUrl), Charset.forName("utf-8"));
    } catch (MalformedURLException exception) {
        invalidURL(environment.getChannel());
        return;
    }
    Prime.Builder primeBuilder = new Prime.Builder()
            .withVariable("guild", new ScriptGuild(environment, environment.getGuild()))
            .withVariable("channel", new ScriptTextChannel(environment, environment.getChannel()))
            .withVariable("user", new ScriptUser(environment, environment.getMember()))
            .withVariable("message", new ScriptMessage(environment, environment.getMessage()))
            .withVariable("embeds", new EmbedMethods())
            .withVariable("commands", new CommandMethods(environment))
            .withVariable("manager", new ManagerMethods(environment))
            .withVariable("storage", new StorageMethods(environment)).withVariable("time", Instant.now())
            .withBlacklistedBindings(Prime.DEFAULT_BINDINGS).withMaxRuntime(10);
    Arrays.stream(PROVIDERS).forEach(primeBuilder::withProvider);
    Prime prime = primeBuilder.build(code);
    prime.evaluate(error);
}