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.simiacryptus.mindseye.lang.Layer.java

/**
 * Eval nn result./*from  w  ww.  j a  va  2 s.  c o  m*/
 *
 * @param array the array
 * @return the nn result
 */
@Nullable
default Result eval(@Nonnull final Tensor... array) {
    Result[] input = ConstantResult.singleResultArray(array);
    Result eval = eval(input);
    Arrays.stream(input).forEach(ReferenceCounting::freeRef);
    Arrays.stream(input).map(Result::getData).forEach(ReferenceCounting::freeRef);
    return eval;
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.FeedsController.java

@GET
@Path("{id}/actions/allowed")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w .jav  a 2s  .  c  o m*/
@ApiOperation("Gets the list of actions permitted for the given username and/or groups.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class),
        @ApiResponse(code = 404, message = "A feed with the given ID does not exist.", response = RestResponseStatus.class) })
public ActionGroup getAllowedActions(@PathParam("id") String feedIdStr,
        @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) {
    LOG.debug("Get allowed actions for feed: {}", feedIdStr);

    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());

    return this.securityService
            .getAllowedFeedActions(feedIdStr,
                    Stream.concat(users.stream(), groups.stream()).collect(Collectors.toSet()))
            .orElseThrow(() -> new WebApplicationException(
                    "A feed with the given ID does not exist: " + feedIdStr, Status.NOT_FOUND));
}

From source file:com.netflix.spinnaker.halyard.config.model.v1.node.Node.java

private Map<String, Object> serializedNonNodeFields() {
    List<Field> fields = Arrays.stream(this.getClass().getDeclaredFields()).filter(f -> {
        return (!(Node.class.isAssignableFrom(f.getType()) || List.class.isAssignableFrom(f.getType())
                || Map.class.isAssignableFrom(f.getType()) || f.getAnnotation(JsonIgnore.class) != null));
    }).collect(Collectors.toList());

    Map<String, Object> res = new HashMap<>();
    for (Field field : fields) {
        field.setAccessible(true);//from w  ww  . java2 s .  c  om
        try {
            res.put(field.getName(), field.get(this));
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to read field " + field.getName() + " in node " + getNodeName());
        }
        field.setAccessible(false);
    }

    return res;
}

From source file:com.oneops.transistor.util.CloudUtil.java

private Stream<String> getServices(CmsRfcRelation cmsRfcRelation) {
    String[] ciRequiredServices = cmsRfcRelation.getAttribute("services").getNewValue().split(",");
    return Arrays.stream(ciRequiredServices).filter(s -> !s.startsWith("*"));
}

From source file:com.shenit.commons.utils.ShenStrings.java

/**
 * Join with seperators./*from   ww  w  . ja  v  a 2 s. co  m*/
 * @param objs
 * @return
 */
public static String joinWithSeperator(Object... objs) {
    if (ShenArrays.isEmpty(objs))
        return org.apache.commons.lang3.StringUtils.EMPTY;
    if (objs.length == 1)
        return str(objs[0]);
    String seperator = str(objs[objs.length - 1]);
    objs = ArrayUtils.remove(objs, objs.length - 1);
    List<String> items = Arrays.stream(objs).filter(item -> item != null).map(item -> {
        if (item.getClass().isArray()) {
            Object[] newObjs = Arrays.copyOf((Object[]) item, len(item) + 1);
            newObjs[newObjs.length - 1] = seperator;
            return joinWithSeperator(newObjs);
        } else {
            return str(item);
        }

    }).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
    return joinAll(items, seperator);
}

From source file:aiai.ai.station.TaskProcessor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;//from  ww w .  ja  v a2s .com
    }
    if (!globals.isStationEnabled) {
        return;
    }
    if (!globals.timePeriods.isCurrentTimeActive()) {
        return;
    }

    File snippetDir = SnippetUtils.checkEvironment(globals.stationDir);
    if (snippetDir == null) {
        return;
    }

    List<StationTask> tasks = stationTaskService.findAllByFinishedOnIsNull();
    for (StationTask task : tasks) {
        if (StringUtils.isBlank(task.getParams())) {
            log.warn("Params for task {} is blank", task.getTaskId());
            continue;
        }
        if (!currentExecState.isStarted(task.flowInstanceId)) {
            continue;
        }
        File taskDir = stationTaskService.prepareTaskDir(task.taskId);

        final TaskParamYaml taskParamYaml = taskParamYamlUtils.toTaskYaml(task.getParams());
        boolean isResourcesOk = true;
        for (String resourceCode : CollectionUtils.toPlainList(taskParamYaml.inputResourceCodes.values())) {
            AssetFile assetFile = StationResourceUtils.prepareResourceFile(taskDir, Enums.BinaryDataType.DATA,
                    resourceCode, null);
            // is this resource prepared?
            if (assetFile.isError || !assetFile.isContent) {
                log.info("Resource hasn't been prepared yet, {}", assetFile);
                isResourcesOk = false;
            }
        }
        if (!isResourcesOk) {
            continue;
        }

        if (taskParamYaml.snippet == null) {
            stationTaskService.finishAndWriteToLog(task, "Broken task. Snippet isn't defined");
            continue;
        }

        File artifactDir = stationTaskService.prepareTaskSubDir(taskDir, "artifacts");
        if (artifactDir == null) {
            stationTaskService.finishAndWriteToLog(task,
                    "Error of configuring of environment. 'artifacts' directory wasn't created, task can't be processed.");
            continue;
        }

        // at this point all required resources have to be downloaded from server

        taskParamYaml.workingPath = taskDir.getAbsolutePath();
        final String params = taskParamYamlUtils.toString(taskParamYaml);

        task.setLaunchedOn(System.currentTimeMillis());
        task = stationTaskService.save(task);
        SimpleSnippet snippet = taskParamYaml.getSnippet();

        AssetFile snippetAssetFile = null;
        if (!snippet.fileProvided) {
            snippetAssetFile = getResource(Enums.BinaryDataType.SNIPPET, snippet.code);
            if (snippetAssetFile == null) {
                snippetAssetFile = StationResourceUtils.prepareResourceFile(globals.stationResourcesDir,
                        Enums.BinaryDataType.SNIPPET, snippet.code, snippet.filename);
                // is this snippet prepared?
                if (snippetAssetFile.isError || !snippetAssetFile.isContent) {
                    log.info("Resource hasn't been prepared yet, {}", snippetAssetFile);
                    isResourcesOk = false;
                } else {
                    putResource(Enums.BinaryDataType.SNIPPET, snippet.code, snippetAssetFile);
                }
            }
            if (!isResourcesOk || snippetAssetFile == null) {
                continue;
            }
        }

        final File paramFile = prepareParamFile(taskDir, Consts.ARTIFACTS_DIR, params);
        if (paramFile == null) {
            break;
        }
        Interpreter interpreter = new Interpreter(stationService.getEnvYaml().getEnvs().get(snippet.env));
        if (interpreter.list == null) {
            log.warn("Can't process the task, the interpreter wasn't found for env: {}", snippet.env);
            break;
        }

        log.info("all system are checked, lift off");

        ExecProcessService.Result result = null;
        try {
            List<String> cmd = Arrays.stream(interpreter.list).collect(Collectors.toList());

            // bug in IDEA with analyzing !snippet.fileProvided, so we have to add '&& snippetAssetFile!=null'
            if (!snippet.fileProvided && snippetAssetFile != null) {
                cmd.add(snippetAssetFile.file.getAbsolutePath());
            }
            if (StringUtils.isNoneBlank(snippet.params)) {
                cmd.addAll(Arrays.stream(StringUtils.split(snippet.params)).collect(Collectors.toList()));
            }
            cmd.add(Consts.ARTIFACTS_DIR + File.separatorChar + Consts.PARAMS_YAML);

            File consoleLogFile = new File(artifactDir, Consts.SYSTEM_CONSOLE_OUTPUT_FILE_NAME);

            // Exec snippet
            result = execProcessService.execCommand(cmd, taskDir, consoleLogFile);

            // Store result
            stationTaskService.storeExecResult(task.getTaskId(), snippet, result, artifactDir);

            if (result.isOk()) {
                File resultDataFile = new File(taskDir,
                        Consts.ARTIFACTS_DIR + File.separatorChar + taskParamYaml.outputResourceCode);
                if (resultDataFile.exists()) {
                    log.info("Register task for uploading result data to server, resultDataFile: {}",
                            resultDataFile.getPath());
                    uploadResourceActor.add(new UploadResourceTask(resultDataFile, task.taskId));
                } else {
                    String es = "Result data file doesn't exist, resultDataFile: " + resultDataFile.getPath();
                    log.error(es);
                    result = new ExecProcessService.Result(false, -1, es);
                }
            }
        } catch (Throwable th) {
            log.error("Error exec process " + interpreter, th);
            result = new ExecProcessService.Result(false, -1, ExceptionUtils.getStackTrace(th));
        }
        stationTaskService.markAsFinishedIfAllOk(task.getTaskId(), result);
    }
}

From source file:com.github.anba.es6draft.util.TestGlobals.java

private static void optionsFromVersion(EnumSet<CompatibilityOption> options, String version) {
    options.addAll(Arrays.stream(CompatibilityOption.Version.values()).filter(v -> {
        return v.name().equalsIgnoreCase(version);
    }).findAny().map(CompatibilityOption::Version).orElseThrow(IllegalArgumentException::new));
}

From source file:eu.itesla_project.online.tools.RunForecastErrorsAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    ComputationManager computationManager = new LocalComputationManager();
    String analysisId = line.getOptionValue("analysis");
    DateTime baseCaseDate = line.hasOption("base-case-date")
            ? DateTime.parse(line.getOptionValue("base-case-date"))
            : getDefaultParameters().getBaseCaseDate();
    Interval histoInterval = line.hasOption("history-interval")
            ? Interval.parse(line.getOptionValue("history-interval"))
            : getDefaultParameters().getHistoInterval();
    double ir = line.hasOption("ir") ? Double.parseDouble(line.getOptionValue("ir"))
            : getDefaultParameters().getIr();
    int flagPQ = line.hasOption("flagPQ") ? Integer.parseInt(line.getOptionValue("flagPQ"))
            : getDefaultParameters().getFlagPQ();
    int method = line.hasOption("method") ? Integer.parseInt(line.getOptionValue("method"))
            : getDefaultParameters().getMethod();
    Integer nClusters = line.hasOption("nClusters") ? Integer.parseInt(line.getOptionValue("nClusters"))
            : getDefaultParameters().getnClusters();
    double percentileHistorical = line.hasOption("percentileHistorical")
            ? Double.parseDouble(line.getOptionValue("percentileHistorical"))
            : getDefaultParameters().getPercentileHistorical();
    Integer modalityGaussian = line.hasOption("modalityGaussian")
            ? Integer.parseInt(line.getOptionValue("modalityGaussian"))
            : getDefaultParameters().getModalityGaussian();
    Integer outliers = line.hasOption("outliers") ? Integer.parseInt(line.getOptionValue("outliers"))
            : getDefaultParameters().getOutliers();
    Integer conditionalSampling = line.hasOption("conditionalSampling")
            ? Integer.parseInt(line.getOptionValue("conditionalSampling"))
            : getDefaultParameters().getConditionalSampling();
    Integer nSamples = line.hasOption("nSamples") ? Integer.parseInt(line.getOptionValue("nSamples"))
            : getDefaultParameters().getnSamples();
    Set<Country> countries = line.hasOption("countries")
            ? Arrays.stream(line.getOptionValue("countries").split(",")).map(Country::valueOf).collect(
                    Collectors.toSet())
            : getDefaultParameters().getCountries();
    CaseType caseType = line.hasOption("case-type") ? CaseType.valueOf(line.getOptionValue("case-type"))
            : getDefaultParameters().getCaseType();

    ForecastErrorsAnalysisParameters parameters = new ForecastErrorsAnalysisParameters(baseCaseDate,
            histoInterval, analysisId, ir, flagPQ, method, nClusters, percentileHistorical, modalityGaussian,
            outliers, conditionalSampling, nSamples, countries, caseType);
    ForecastErrorsAnalysis feAnalysis = new ForecastErrorsAnalysis(computationManager,
            ForecastErrorsAnalysisConfig.load(), parameters);
    System.out.println("Starting Forecast Errors Analysis");
    if (line.hasOption("time-horizon")) {
        TimeHorizon timeHorizon = TimeHorizon.fromName(line.getOptionValue("time-horizon"));
        feAnalysis.start(timeHorizon);/*ww  w  .ja v a  2s .  c om*/
    } else
        feAnalysis.start();
    System.out.println("Forecast Errors Analysis Terminated");
}

From source file:com.github.aptd.simulation.CMain.java

/**
 * returns the experiment data models/*from   w w w.java 2s  .co  m*/
 *
 * @param p_options commandline options
 * @return stream of experiments
 */
private static Stream<Pair<EDataModel, String>> datamodel(final CommandLine p_options) {
    final List<String> l_instances = Arrays.stream(p_options.getOptionValue("scenario").split(","))
            .map(String::trim).filter(i -> !i.isEmpty()).collect(Collectors.toList());

    final List<String> l_types = Arrays.stream(p_options.getOptionValue("scenariotype", "").split(","))
            .map(String::trim).filter(i -> !i.isEmpty()).collect(Collectors.toList());

    return StreamUtils.zip(l_instances.stream(),
            Stream.concat(l_types.stream(),
                    IntStream.range(0, l_instances.size() - l_types.size()).mapToObj(
                            i -> CConfiguration.INSTANCE.getOrDefault("xml", "default", "datamodel"))),
            (i, j) -> new ImmutablePair<>(EDataModel.from(j), i));
}

From source file:org.jboss.as.test.integration.management.extension.customcontext.testbase.CustomManagementContextTestBase.java

private void test(final ManagementClient managementClient) throws IOException {
    //if (true) return;

    final String urlBase = "http://" + managementClient.getMgmtAddress() + ":9990/";
    final String remapUrl = urlBase + "remap/foo";
    final String badRemapUrl = urlBase + "remap/bad";
    final String staticUrl = urlBase + "static/hello.txt";
    final String staticUrlDirectory = urlBase + "static/";
    final String badStaticUrl = urlBase + "static/bad.txt";

    // Sanity check

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpResponse resp = client.execute(new HttpGet(remapUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());
        resp = client.execute(new HttpGet(staticUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());
    }//from  w  w w .ja  va 2  s. c  om

    // Add extension and subsystem

    executeOp(Util.createAddOperation(getExtensionAddress()), managementClient);
    executeOp(Util.createAddOperation(getSubsystemAddress()), managementClient);

    // Unauthenticated check

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpResponse resp = client.execute(new HttpGet(remapUrl));
        assertEquals(401, resp.getStatusLine().getStatusCode());
        resp = client.execute(new HttpGet(staticUrl));
        assertEquals(200, resp.getStatusLine().getStatusCode());
    }

    try (CloseableHttpClient client = createAuthenticatingClient(managementClient)) {

        // Authenticated check

        HttpResponse resp = client.execute(new HttpGet(remapUrl));
        assertEquals(200, resp.getStatusLine().getStatusCode());
        ModelNode respNode = ModelNode.fromJSONString(EntityUtils.toString(resp.getEntity()));
        assertEquals(respNode.toString(), CustomContextExtension.EXTENSION_NAME,
                respNode.get("module").asString());
        assertTrue(respNode.toString(), respNode.hasDefined("subsystem"));
        assertTrue(respNode.toString(), respNode.get("subsystem").has(CustomContextExtension.SUBSYSTEM_NAME));

        resp = client.execute(new HttpGet(staticUrl));
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String text = EntityUtils.toString(resp.getEntity());
        assertTrue(text, text.startsWith("Hello"));

        // the response should contain headers:
        // X-Frame-Options: SAMEORIGIN
        // Cache-Control: public, max-age=2678400
        final Map<String, String> headersMap = Arrays.stream(resp.getAllHeaders())
                .collect(Collectors.toMap(Header::getName, Header::getValue));
        Assert.assertTrue("'X-Frame-Options: SAMEORIGIN' header is expected",
                headersMap.getOrDefault("X-Frame-Options", "").contains("SAMEORIGIN"));
        Assert.assertTrue("Cache-Control header with max-age=2678400 is expected,",
                headersMap.getOrDefault("Cache-Control", "").contains("max-age=2678400"));

        // directory listing is not allowed
        resp = client.execute(new HttpGet(staticUrlDirectory));
        assertEquals(404, resp.getStatusLine().getStatusCode());

        // POST check
        resp = client.execute(new HttpPost(remapUrl));
        assertEquals(405, resp.getStatusLine().getStatusCode());
        resp = client.execute(new HttpPost(staticUrl));
        assertEquals(200, resp.getStatusLine().getStatusCode());

        // Bad URL check

        resp = client.execute(new HttpGet(badRemapUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());
        resp = client.execute(new HttpGet(badStaticUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());

        // Remove subsystem

        executeOp(Util.createRemoveOperation(getSubsystemAddress()), managementClient);

        // Requests fail

        resp = client.execute(new HttpGet(remapUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());
        resp = client.execute(new HttpGet(staticUrl));
        assertEquals(404, resp.getStatusLine().getStatusCode());
    }
}