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

private static void multipartUpload(EncryptedServerSideMultipartManager multipart) {
    String uploadObject = "/" + mantaUsername + "/stor/multipart";

    // We catch network errors and handle them here
    try {// ww w.  ja  v a2s . c om
        MantaMetadata metadata = new MantaMetadata();
        metadata.put("e-secretkey", "My Secret Value");
        EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(uploadObject,
                metadata);
        MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, RandomUtils.nextBytes(5242880));
        MantaMultipartUploadPart part2 = multipart.uploadPart(upload, 2, RandomUtils.nextBytes(1000000));

        // Complete the process by instructing Manta to assemble the final object from its parts
        MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1, part2 };
        Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts);
        multipart.complete(upload, partsStream);

        System.out.println(uploadObject + " is now assembled!");
    } catch (IOException e) {
        // This catch block is for general network failures
        // For example, ServerSideMultipartUpload.initiateUpload can throw an IOException

        ContextedRuntimeException exception = new ContextedRuntimeException(
                "A network error occurred when doing a multipart upload to Manta.");
        exception.setContextValue("path", uploadObject);

        throw exception;
    }
}

From source file:com.netflix.spinnaker.halyard.config.validate.v1.FieldValidator.java

private void validateFieldForSpinnakerVersion(ConfigProblemSetBuilder p, Node n) {
    DeploymentConfiguration deploymentConfiguration = n.parentOfType(DeploymentConfiguration.class);
    String spinnakerVersion = deploymentConfiguration.getVersion();
    if (spinnakerVersion == null) {
        return;/*from w w  w  .  j av  a  2  s .  c om*/
    }

    Class clazz = n.getClass();
    while (clazz != Object.class) {
        Class finalClazz = clazz;
        Arrays.stream(clazz.getDeclaredFields()).forEach(field -> {
            ValidForSpinnakerVersion annotation = field.getDeclaredAnnotation(ValidForSpinnakerVersion.class);
            try {
                field.setAccessible(true);
                Object v = field.get(n);
                boolean fieldNotValid = false;
                String invalidFieldMessage = "";
                String remediation = "";
                if (v != null && annotation != null) {
                    if (Versions.lessThan(spinnakerVersion, annotation.lowerBound())) {
                        fieldNotValid = true;
                        invalidFieldMessage = annotation.tooLowMessage();
                        remediation = "Use at least " + annotation.lowerBound()
                                + " (It may not have been released yet).";
                    } else if (!StringUtils.equals(annotation.upperBound(), "")
                            && Versions.greaterThanEqual(spinnakerVersion, annotation.upperBound())) {
                        fieldNotValid = true;
                        invalidFieldMessage = annotation.tooHighMessage();
                        remediation = "You no longer need this.";
                    }
                }

                // If the field was set to false, it's assumed it's not enabling a restricted feature
                if (fieldNotValid && (v instanceof Boolean) && !((Boolean) v)) {
                    fieldNotValid = false;
                }

                // If the field is a collection, it may be empty
                if (fieldNotValid && (v instanceof Collection) && ((Collection) v).isEmpty()) {
                    fieldNotValid = false;
                }

                if (fieldNotValid) {
                    p.addProblem(Problem.Severity.WARNING,
                            "Field " + finalClazz.getSimpleName() + "." + field.getName()
                                    + " not supported for Spinnaker version " + spinnakerVersion + ": "
                                    + invalidFieldMessage)
                            .setRemediation(remediation);
                }
            } catch (NumberFormatException /* Probably using nightly build */ e) {
                log.info("Nightly builds do not contain version information.");
            } catch (IllegalAccessException /* Probably shouldn't happen */ e) {
                log.warn("Error validating field " + finalClazz.getSimpleName() + "." + field.getName() + ": ",
                        e);
            }
        });
        clazz = clazz.getSuperclass();
    }
}

From source file:ee.ria.xroad.common.certificateprofile.impl.AbstractCertificateProfileInfo.java

@Override
public X500Principal createSubjectDn(DnFieldValue[] values) {
    return new X500Principal(
            StringUtils.join(Arrays.stream(values).map(this::toString).collect(Collectors.toList()), ", "));
}

From source file:eu.openanalytics.shinyproxy.UISecurityConfig.java

@Override
public void apply(HttpSecurity http) throws Exception {
    if (auth.hasAuthorization()) {

        // Limit access to the app pages according to spec permissions
        for (ProxySpec spec : proxyService.getProxySpecs(null, true)) {
            if (spec.getAccessControl() == null)
                continue;

            String[] groups = spec.getAccessControl().getGroups();
            if (groups == null || groups.length == 0)
                continue;

            String[] appGroups = Arrays.stream(groups).map(s -> s.toUpperCase()).toArray(i -> new String[i]);
            http.authorizeRequests().antMatchers("/app/" + spec.getId()).hasAnyRole(appGroups);
        }/* ww w.  j  a  v a2  s  . c o m*/

        // Limit access to the admin pages
        http.authorizeRequests().antMatchers("/admin").hasAnyRole(userService.getAdminGroups());
    }
}

From source file:com.intuit.wasabi.repository.cassandra.ClientConfiguration.java

@Override
public List<String> getNodeHosts() {
    return Arrays.stream(getProperty("nodeHosts", properties).split(",")).map(String::trim)
            .collect(Collectors.toList());
}

From source file:edu.brandeis.wisedb.scheduler.experiments.SkewDistributionExperiment.java

public static void calculateBurn(int samples) throws Exception {
    TightenableSLA sla = PercentSLA.nintyTenSLA();
    //TightenableSLA sla = new SimpleLatencyModelSLA(9 * 60 * 1000, 1);
    //TightenableSLA sla = PerQuerySLA.getLatencyTimesN(2.0);
    //TightenableSLA sla = new AverageLatencyModelSLA(7 * 60 * 1000, 1);
    QueryTimePredictor qtp = new QueryTimePredictor();

    File f = new File("distSkew.csv");
    if (f.exists())
        f.delete();//from  w w w. j  ava2  s  .c om

    try (Trainer t = new Trainer("distSkew.csv", sla)) {
        t.train(2000, 12);
    }

    DTSearcher dt = new DTSearcher("distSkew.csv", qtp, sla);
    AStarGraphSearch astar = new AStarGraphSearch(new UnassignedQueryTimeHeuristic(qtp), sla, qtp);
    //FirstFitDecreasingGraphSearch astar = new FirstFitDecreasingGraphSearch(sla, qtp);

    ChiSquareTest cst = new ChiSquareTest();
    ChiSquaredDistribution cqd = new ChiSquaredDistribution(qtp.QUERY_TYPES.length - 1);
    double[] expceted = Arrays.stream(qtp.QUERY_TYPES).mapToDouble(i -> 20.0 / (qtp.QUERY_TYPES.length))
            .toArray();

    System.out.println("Chi\tDT\tOpt");

    for (int i = 0; i < samples; i++) {
        Set<ModelQuery> smp = ModelWorkloadGenerator.randomQueries(20);

        // reject samples that don't have at least one of each query type
        long repr = smp.stream().mapToInt(q -> q.getType()).distinct().count();
        if (repr != qtp.QUERY_TYPES.length) {
            i--;
            continue;
        }

        Map<Integer, List<ModelQuery>> groups = smp.stream().collect(Collectors.groupingBy(q -> q.getType()));

        long obs[] = Arrays.stream(qtp.QUERY_TYPES).mapToLong(v -> groups.get(v).size()).toArray();

        double chi = cst.chiSquare(expceted, obs);
        chi = cqd.cumulativeProbability(chi);

        Cost dtCost = dt.getCostForQueries(smp, sla);
        Cost optCost = astar.getCostForQueries(smp, sla);

        System.out.println(chi + "\t" + dtCost.getTotalCost() + "\t" + optCost.getTotalCost());
    }

}

From source file:io.github.jeddict.jcode.util.PersistenceUtil.java

public static void addProperty(PersistenceUnit punit, String key, String value) {
    Properties properties = punit.getProperties();
    if (properties == null) {
        properties = punit.newProperties();
        punit.setProperties(properties);
    }//from  w w  w .  j a va2 s  .c o m
    Property property = properties.newProperty();
    property.setName(key);
    property.setValue(value);

    Property existing = getProperty(properties.getProperty2(), key);

    if (existing != null) {
        existing.setValue(property.getValue());
    } else {
        properties.addProperty2(property);
    }
    System.out.println(Arrays.stream(punit.getProperties().getProperty2())
            .map(p -> p.getName() + '.' + p.getValue()).collect(Collectors.joining("|", "<", ">")));
}

From source file:com.github.ambry.commons.BlobIdTest.java

/**
 * Running for both {@link BlobId#BLOB_ID_V1} and {@link BlobId#BLOB_ID_V2}
 * @return an array with both {@link BlobId#BLOB_ID_V1} and {@link BlobId#BLOB_ID_V2}
 *//* www  .  j  a  v a 2s.  co  m*/
@Parameterized.Parameters
public static List<Object[]> data() {
    return Arrays.stream(BlobId.getAllValidVersions()).map(version -> new Object[] { version })
            .collect(Collectors.toList());
}

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

@JsonIgnore
public Map<SpinnakerService.Type, ServiceSettings> getAllServiceSettings() {
    return Arrays.stream(Services.class.getDeclaredFields()).reduce(new HashMap<>(), (map, field) -> {
        if (!ServiceSettings.class.isAssignableFrom(field.getType())) {
            return map;
        }//from w  w w .j  ava 2 s.  c  om

        SpinnakerService.Type type = SpinnakerService.Type.fromCanonicalName(field.getName());
        ServiceSettings settings;
        try {
            settings = (ServiceSettings) field.get(services);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        if (settings != null) {
            map.put(type, settings);
        }

        return map;
    }, (map1, map2) -> {
        map1.putAll(map2);
        return map1;
    });
}

From source file:io.github.jeddict.orm.generator.compiler.constraints.EmailSnippet.java

public EmailSnippet(Email email) {
    super(email);
    if (isNotBlank(constraint.getFlags())) {
        flags = Arrays.stream(constraint.getFlags().split(",")).map(flag -> Flag.fromValue(flag.trim()))
                .filter(flag -> flag != null).collect(toList());
    }//ww  w . j  av  a 2  s  .  c o  m
}