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:me.rkfg.xmpp.bot.plugins.CoolStoryPlugin.java

@Override
public String getManual() {
    return Stream.concat(Stream.of(HELP_AVAILABLE_COMMANDS), Arrays.stream(WEBSITES).map(Website::getHelp))
            .collect(Collectors.joining("\n"));
}

From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java

private Object createBeanProxy(Object bean) {
    MethodInterceptor handler = invocation -> {
        Method method = invocation.getMethod();
        switch (method.getName()) {
        case "hashCode":
            return hashCode();
        case "equals":
            return (invocation.getThis() == invocation.getArguments()[0]);
        case "toString":
            return toString();
        }//from   w  w  w .  j  a  va 2  s  .c o m

        if (entityManagerLocal.get() == null && !method.isAnnotationPresent(IgnoreCamelEntityManager.class)) {
            Arrays.stream(invocation.getArguments()).filter(f -> f instanceof Exchange).findFirst()
                    .map(Exchange.class::cast)
                    .map(o -> o.getIn().getHeader(CAMEL_ENTITY_MANAGER, EntityManager.class))
                    .ifPresent(em -> addThreadLocalEntityManager(em));
        }
        return invocation.proceed();
    };

    ProxyFactory factory = new ProxyFactory(bean);
    factory.addAdvice(handler);

    return factory.getProxy();
}

From source file:com.thinkbiganalytics.security.rest.controller.AccessControlController.java

@GET
@Path("{name}/allowed")
@Produces(MediaType.APPLICATION_JSON)/* w  w  w .  j a va  2  s . c  om*/
@ApiOperation("Gets the list of allowed actions for a principal.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class),
        @ApiResponse(code = 404, message = "The given name was not found.", response = RestResponseStatus.class) })
public ActionGroup getAllowedActions(@PathParam("name") String moduleName,
        @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) {

    Set<? extends Principal> users = Arrays.stream(this.actionsTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.actionsTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());
    Principal[] principals = Stream.concat(users.stream(), groups.stream()).toArray(Principal[]::new);

    // Retrieve the allowed actions by executing the query as the specified user/groups 
    return metadata.read(() -> {
        return actionsProvider.getAllowedActions(moduleName)
                .map(this.actionsTransform.toActionGroup(AllowedActions.SERVICES))
                .orElseThrow(() -> new WebApplicationException("The available service actions were not found",
                        Status.NOT_FOUND));
    }, principals);
}

From source file:cc.altruix.javaprologinterop.PlUtilsLogic.java

protected void addVariableValues(String query, String[] varNames, Map<String, String> row, SolveInfo res2l) {
    Arrays.stream(varNames).forEach(varName -> {
        try {//w  w w .ja v  a2 s.c  om
            row.put(varName, res2l.getTerm(varName).toString());
        } catch (NoSolutionException | UnknownVarException exception) {
            printError(query, varNames, exception);
        }
    });
}

From source file:com.intellij.plugins.haxe.model.HaxeFileModel.java

public Stream<HaxeClassModel> getClassModelsStream() {
    return Arrays.stream(file.getChildren()).filter(element -> element instanceof HaxeClass)
            .map(element -> ((HaxeClass) element).getModel());
}

From source file:org.elasticsearch.packaging.test.ArchiveTestCase.java

public void test30AbortWhenJavaMissing() {
    assumeThat(installation, is(notNullValue()));

    final Installation.Executables bin = installation.executables();
    final Shell sh = new Shell();

    Platforms.onWindows(() -> {/*from  w  w  w. j a  v  a  2s .c o  m*/
        // on windows, removing java from PATH and removing JAVA_HOME is less involved than changing the permissions of the java
        // executable. we also don't check permissions in the windows scripts anyway
        final String originalPath = sh.run("$Env:PATH").stdout.trim();
        final String newPath = Arrays.stream(originalPath.split(";"))
                .filter(path -> path.contains("Java") == false).collect(joining(";"));

        // note the lack of a $ when clearing the JAVA_HOME env variable - with a $ it deletes the java home directory
        // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/providers/environment-provider?view=powershell-6
        //
        // this won't persist to another session so we don't have to reset anything
        final Result runResult = sh.runIgnoreExitCode(
                "$Env:PATH = '" + newPath + "'; " + "Remove-Item Env:JAVA_HOME; " + bin.elasticsearch);

        assertThat(runResult.exitCode, is(1));
        assertThat(runResult.stderr,
                containsString("could not find java; set JAVA_HOME or ensure java is in PATH"));
    });

    Platforms.onLinux(() -> {
        final String javaPath = sh.run("command -v java").stdout.trim();

        try {
            sh.run("chmod -x '" + javaPath + "'");
            final Result runResult = sh.runIgnoreExitCode(bin.elasticsearch.toString());
            assertThat(runResult.exitCode, is(1));
            assertThat(runResult.stdout,
                    containsString("could not find java; set JAVA_HOME or ensure java is in PATH"));
        } finally {
            sh.run("chmod +x '" + javaPath + "'");
        }
    });
}

From source file:webfx.URLVerifier.java

private void discoverThroughHeaders() throws IOException, URISyntaxException {
    // relax redirections
    HttpGet httpGet = new HttpGet(location.toURI());
    HttpClientContext httpcontext = HttpClientContext.create();
    try (CloseableHttpResponse response = httpclient.execute(httpGet, httpcontext)) {
        // get mimetype via Content-Type http header
        Arrays.stream(response.getHeaders("Content-Type")).findFirst()
                .ifPresent(h -> this.contentType = h.getValue());
        if (!Objects.isNull(contentType)) {
            contentType = contentType.contains(";") ? contentType.substring(0, contentType.indexOf(";")).trim()
                    : contentType;//from  w w w  .j a v  a 2  s.c o  m
            LOGGER.log(Level.INFO, "Final Content-Type: {0}", contentType);
        } else {
            LOGGER.log(Level.INFO, "Content-Type Header is Empty: {0}",
                    Arrays.toString(response.getHeaders("Content-Type")));
            // clear field b/c it was used inside lambda as temp var
            contentType = null;
        }

        // get filename via Content-Disposition http header
        Arrays.stream(response.getHeaders("Content-Disposition")).findFirst()
                .ifPresent(h -> this.pageName = h.getValue());
        if (!Objects.isNull(pageName) && pageName.contains("filename=")) {
            pageName = pageName.substring(pageName.lastIndexOf("filename=") + 9);
            LOGGER.log(Level.INFO, "temporary page name: {0}", pageName);
            if (pageName.indexOf('.') > -1) {
                fileExtension = pageName.substring(pageName.indexOf('.') + 1).trim();
                LOGGER.log(Level.INFO, "Final file extension: {0}", fileExtension);
            }
            pageName = pageName.substring(0, pageName.indexOf('.')).trim();
            LOGGER.log(Level.INFO, "Final page name: {0}", pageName);
        } else {
            // clear field b/c it was used inside lambda as temp var
            pageName = null;
        }

        HttpHost target = httpcontext.getTargetHost();
        List<URI> redirectLocations = httpcontext.getRedirectLocations();
        URI _loc = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
        this.location = _loc.toURL();
        LOGGER.log(Level.INFO, "Final HTTP location: {0}", _loc.toURL());
    }
}

From source file:com.qq.tars.service.server.ServerService.java

public ServerConf getServerConf4Tree(String treeNodeId) {
    ServerConf serverConf = new ServerConf();
    AtomicBoolean enableSet = new AtomicBoolean(false);
    Arrays.stream(treeNodeId.split("\\.")).forEach(s -> {
        int i = Integer.parseInt(s.substring(0, 1));
        String v = s.substring(1);
        switch (i) {
        case 1://w w  w  .j a v  a2  s.co m
            serverConf.setApplication(v);
            break;
        case 2:
            serverConf.setSetName(v);
            enableSet.set(true);
            break;
        case 3:
            serverConf.setSetArea(v);
            enableSet.set(true);
            break;
        case 4:
            serverConf.setSetGroup(v);
            enableSet.set(true);
            break;
        case 5:
            serverConf.setServerName(v);
            break;
        default:
            break;
        }
    });
    serverConf.setEnableSet(enableSet.get() ? "Y" : "N");
    return serverConf;
}

From source file:org.jimsey.projects.turbine.condenser.service.ElasticsearchNativeServiceImpl.java

@Override
public String getAllTicks() {
    QueryBuilder queryBuilder = matchAllQuery();
    SearchResponse response = elasticsearch.prepareSearch(indexForTicks).setQuery(queryBuilder)
            .setTypes(typeForTicks).setSize(size).get();
    // for (SearchHit hit : response.getHits().getHits()) {
    // System.out.println(hit.getSourceAsString());
    // }/* ww w. ja  v  a2 s  . c  o  m*/
    String results = Arrays.stream(response.getHits().getHits()).map(hit -> hit.getSourceAsString())
            .reduce((a, b) -> String.format("%s,%s", a, b)).orElse("");
    return String.format("[%s]", results);
}

From source file:org.apache.nifi.minifi.c2.provider.nifi.rest.NiFiRestConfigurationProvider.java

@Override
public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters)
        throws ConfigurationProviderException {
    if (!CONTENT_TYPE.equals(contentType)) {
        throw new ConfigurationProviderException(
                "Unsupported content type: " + contentType + " supported value is " + CONTENT_TYPE);
    }/*  w  w  w.j  a  v a  2s  . c om*/
    String filename = templateNamePattern;
    for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
        if (entry.getValue().size() != 1) {
            throw new InvalidParameterException(
                    "Multiple values for same parameter not supported in this provider.");
        }
        filename = filename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0));
    }
    int index = filename.indexOf("${");
    while (index != -1) {
        int endIndex = filename.indexOf("}", index);
        if (endIndex == -1) {
            break;
        }
        String variable = filename.substring(index + 2, endIndex);
        if (!"version".equals(variable)) {
            throw new InvalidParameterException("Found unsubstituted parameter " + variable);
        }
        index = endIndex + 1;
    }

    String id = null;
    if (version == null) {
        String filenamePattern = Arrays.stream(filename.split(Pattern.quote("${version}"), -1))
                .map(Pattern::quote).collect(Collectors.joining("([0-9+])"));
        Pair<String, Integer> maxIdAndVersion = getMaxIdAndVersion(filenamePattern);
        id = maxIdAndVersion.getFirst();
        version = maxIdAndVersion.getSecond();
    }
    filename = filename.replaceAll(Pattern.quote("${version}"), Integer.toString(version));
    WriteableConfiguration configuration = configurationCache.getCacheFileInfo(contentType, parameters)
            .getConfiguration(version);
    if (configuration.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Configuration " + configuration + " exists and can be served from configurationCache.");
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Configuration " + configuration
                    + " doesn't exist, will need to download and convert template.");
        }
        if (id == null) {
            try {
                String tmpFilename = templateNamePattern;
                for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
                    if (entry.getValue().size() != 1) {
                        throw new InvalidParameterException(
                                "Multiple values for same parameter not supported in this provider.");
                    }
                    tmpFilename = tmpFilename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"),
                            entry.getValue().get(0));
                }
                Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream();
                try {
                    String finalFilename = filename;
                    id = streamCloseablePair.getFirst().filter(p -> finalFilename.equals(p.getSecond()))
                            .map(Pair::getFirst).findFirst().orElseThrow(() -> new InvalidParameterException(
                                    "Unable to find template named " + finalFilename));
                } finally {
                    streamCloseablePair.getSecond().close();
                }
            } catch (IOException | TemplatesIteratorException e) {
                throw new ConfigurationProviderException("Unable to retrieve template list", e);
            }
        }

        HttpURLConnection urlConnection = httpConnector.get("/templates/" + id + "/download");

        try (InputStream inputStream = urlConnection.getInputStream()) {
            ConfigSchema configSchema = ConfigMain.transformTemplateToSchema(inputStream);
            SchemaSaver.saveConfigSchema(configSchema, configuration.getOutputStream());
        } catch (IOException e) {
            throw new ConfigurationProviderException(
                    "Unable to download template from url " + urlConnection.getURL(), e);
        } catch (JAXBException e) {
            throw new ConfigurationProviderException("Unable to convert template to yaml", e);
        } finally {
            urlConnection.disconnect();
        }
    }
    return configuration;
}