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:ijfx.ui.previewToolbar.DefaultWidget.java

@Override
public Image getImage(PreviewService previewService, int size) {

    if (image != null)
        return image;

    if (previewService == null)
        return null;

    if (previewService.getImageDisplayService().getActiveDataset() == null) {
        return null;
    } else if (this.getIcon().equals("preview")) {
        try {//from  ww  w.j a v a 2  s.  c  om
            previewService.setParameters(-1, -1, size, size);
            return previewService.getImageDisplay(action, this.getParameters());

        } catch (Exception e) {
            e.printStackTrace();
            FontAwesomeIconView fontAwesomeIconView = new FontAwesomeIconView(FontAwesomeIcon.AMBULANCE);
            return FontAwesomeIconUtils.FAItoImage(fontAwesomeIconView, size);
        }
    }

    else if (getIcon().startsWith("char:")) {
        Canvas canvas = new Canvas(size, size);
        GraphicsContext graphicsContext2D = canvas.getGraphicsContext2D();

        graphicsContext2D.setFill(Color.WHITE);
        graphicsContext2D.setFont(javafx.scene.text.Font.font("Arial", size));
        graphicsContext2D.fillText(getIcon().substring(5), size / 3, size * 0.8);

        final SnapshotParameters params = new SnapshotParameters();
        params.setFill(Color.TRANSPARENT);
        //            final WritableImage snapshot = canvas.snapshot(params, null);

        Task<WritableImage> getIcon = new CallbackTask<Canvas, WritableImage>(canvas)
                .run(input -> input.snapshot(params, null));

        Platform.runLater(getIcon);

        try {
            // Image image = new Ima

            image = getIcon.get();
            return image;
        } catch (InterruptedException ex) {
            Logger.getLogger(DefaultWidget.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(DefaultWidget.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    //Check if icon exist in Enumeration
    else if (Arrays.stream(FontAwesomeIcon.values()).filter(e -> e.name().equals(icon)).count() > 0) {

        FontAwesomeIconView fontAwesomeIconView = new FontAwesomeIconView(FontAwesomeIcon.valueOf(icon));
        return FontAwesomeIconUtils.FAItoImage(fontAwesomeIconView, size);
    } else {
        image = new Image(getClass().getResource(icon).toExternalForm(), size, size, true, true);
        return image;
    }
}

From source file:com.github.ukase.service.BulkRenderer.java

private void checkDataDirectory() {
    File[] directories = path.listFiles();
    if (directories == null) {
        return;/*  www . jav  a2s  .co m*/
    }
    Arrays.stream(directories).forEach(this::checkSubDirectories);
}

From source file:org.age.services.worker.internal.DefaultWorkerService.java

protected DefaultWorkerService() {
    Arrays.stream(WorkerMessage.Type.values()).forEach(type -> workerMessageListeners.put(type, newHashSet()));

    messageHandlers.put(WorkerMessage.Type.LOAD_CLASS, this::handleLoadClass);
    messageHandlers.put(WorkerMessage.Type.LOAD_CONFIGURATION, this::handleLoadConfig);
    messageHandlers.put(WorkerMessage.Type.START_COMPUTATION, this::handleStartComputation);
}

From source file:fr.cph.stock.external.impl.ExternalDataAccessImpl.java

@Override
public final Stream<CurrencyData> getCurrencyData(final Currency currency) {
    return Arrays.stream(Currency.values()).filter(c -> c != currency).flatMap(c -> {
        final StringBuilder sb = new StringBuilder();
        sb.append("\"").append(currency.getCode()).append(c.getCode()).append("\",\"").append(c.getCode())
                .append(currency.getCode()).append("\"");
        final String request = "select * from yahoo.finance.xchange where pair in (" + sb + ")";
        final XChangeResult xChangeResult = yahooGateway.getObject(request, XChangeResult.class);
        if (xChangeResult.getQuery().getResults() == null) {
            log.error("The YQL http request worked but the response did not contain any results");
            throw new YahooException("Error while refreshing currencies");
        }/*from w ww .  j  a  v a2  s .  c o m*/
        final List<Rate> rates = xChangeResult.getQuery().getResults().getRate();
        if (rates != null && rates.size() == 2) {
            final CurrencyData currencyData = CurrencyData.builder().currency1(currency).currency2(c)
                    .value(rates.get(0).getRate()).build();
            final CurrencyData currencyData2 = CurrencyData.builder().currency1(c).currency2(currency)
                    .value(rates.get(1).getRate()).build();
            return Stream.of(currencyData, currencyData2);
        } else {
            log.error("Could not find currency data: {}", xChangeResult);
            return Stream.empty();
        }
    });
}

From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java

@PostConstruct
private void initialize() {
    try {// w w w .j  a v  a  2s . c  o  m
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        // Enable SSL if the `mongossl` Profile is enabled
        if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> env.equalsIgnoreCase("mongossl"))) {
            builder.sslEnabled(true);
            builder.sslInvalidHostNameAllowed(true);
        }
        // If a username and password are provided, then associate these credentials with the connection
        if ((!StringUtils.isEmpty(DATABASE_USERNAME)) && (!StringUtils.isEmpty(DATABASE_CREDENTIAL))) {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    Arrays.asList(MongoCredential.createCredential(DATABASE_USERNAME, DATABASE_NAME,
                            DATABASE_CREDENTIAL.toCharArray())),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        } else {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        }

    } catch (Exception exception) {
        LOGGER.error(String.format("Error connecting to MongoDB Instance. %s", exception.getMessage()),
                exception);

    }
}

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

@Override
public List<HaxeModel> getExposedMembers() {
    PsiDirectory directory = root.access(path);
    if (directory != null) {
        PsiFile[] files = directory.getFiles();

        return Arrays.stream(files).filter(file -> file instanceof HaxeFile).map(file -> {
            HaxeFileModel fileModel = HaxeFileModel.fromElement(file);
            return fileModel != null ? fileModel.getMainClassModel() : null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }/*  w  ww  .  j a  v  a2 s.  c  o m*/

    return Collections.emptyList();
}

From source file:com.joyent.manta.client.multipart.EncryptedServerSideMultipartManagerSerializationIT.java

public final void canResumeUploadWithByteArrayAndMultipleParts() throws Exception {
    final SupportedCipherDetails cipherDetails = SupportedCiphersLookupMap.INSTANCE
            .get(config.getEncryptionAlgorithm());
    final SecretKey secretKey = SecretKeyUtils.loadKey(config.getEncryptionPrivateKeyBytes(), cipherDetails);
    final EncryptedMultipartUploaSerializationHelper<ServerSideMultipartUpload> helper = new EncryptedMultipartUploaSerializationHelper<>(
            kryo, secretKey, cipherDetails, ServerSideMultipartUpload.class);
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final byte[] content = RandomUtils.nextBytes(FIVE_MB + 1024);
    final byte[] content1 = Arrays.copyOfRange(content, 0, FIVE_MB + 1);
    final byte[] content2 = Arrays.copyOfRange(content, FIVE_MB + 1, FIVE_MB + 1024);

    String contentType = "application/something-never-seen-before; charset=UTF-8";
    MantaHttpHeaders headers = new MantaHttpHeaders();
    headers.setContentType(contentType);

    EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(path, null, headers);
    MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, content1);

    Provider provider = upload.getEncryptionState().getEncryptionContext().getCipher().getProvider();

    LOGGER.info("Testing serialization with encryption provider: {}", provider.getInfo());

    final byte[] serializedEncryptionState = helper.serialize(upload);

    EncryptedMultipartUpload<ServerSideMultipartUpload> deserializedUpload = helper
            .deserialize(serializedEncryptionState);

    MantaMultipartUploadPart part2 = multipart.uploadPart(deserializedUpload, 2, content2);
    MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1, part2 };
    Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts);

    multipart.complete(deserializedUpload, partsStream);

    try (MantaObjectInputStream in = mantaClient.getAsInputStream(path)) {
        Assert.assertEquals(in.getContentType(), contentType,
                "Set content-type doesn't match actual content type");

        int b;//from w w  w . j  a  va2  s .  c  o  m
        int i = 0;
        while ((b = in.read()) != -1) {
            final byte expected = content[i++];

            Assert.assertEquals((byte) b, expected,
                    "Byte [" + (char) b + "] not matched at position: " + (i - 1));
        }

        if (i + 1 < content.length) {
            fail("Missing " + (content.length - i + 1) + " bytes from Manta stream");
        }
    }
}

From source file:com.ejisto.modules.executor.TaskManager.java

public static <T> GuiTask<T> createNewGuiTask(Callable<T> callable, String description,
        PropertyChangeListener... listeners) {
    GuiTask<T> task = new GuiTask<>(callable, description);
    Arrays.stream(listeners).forEach(task::addPropertyChangeListener);
    return task;// w w w.  j  a v  a  2 s. c  o m
}

From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java

private Constructor getEventHandlerConstructor(DomainEvent event) {
    Set<Constructor> constructors = Arrays.stream(targetClass.getConstructors())
            .filter(contructor -> contructor.isAnnotationPresent(ConstructionHandler.class))
            .collect(Collectors.toSet());
    for (Constructor constructor : constructors) {
        ConstructionHandler constructionHandlerAnnotation = (ConstructionHandler) constructor
                .getAnnotation(ConstructionHandler.class);
        if (constructionHandlerAnnotation.value().equals(event.getClass())) {
            return constructor;
        }//from  ww  w.  j av  a2s .co  m
    }
    return null;
}

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

/**
 * check package translation configuration versus property items
 *//* w w  w.ja  va  2s.  c om*/
@Test
public void testTranslation() {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    // --- read language definitions from the configuration
    final Set<String> l_translation = Collections.unmodifiableSet(
            Arrays.stream(CCommon.configuration().getObject("translation").toString().split(","))
                    .map(i -> i.trim().toLowerCase()).collect(Collectors.toSet()));

    // --- check if a test (language resource) exists for each definied language
    final Set<String> l_translationtesting = new HashSet<>(l_translation);
    l_translationtesting.removeAll(LANGUAGEPROPERY.keySet());
    assertFalse(MessageFormat.format(
            "configuration defines {1,choice,1#translation|1<translations} {0} that {1,choice,1#is|1<are} not tested",
            l_translationtesting, l_translationtesting.size()), !l_translationtesting.isEmpty());

    // --- check unused language resource files
    final Set<String> l_translationusing = new HashSet<>(LANGUAGEPROPERY.keySet());
    l_translationusing.removeAll(l_translation);
    assertFalse(MessageFormat.format(
            "{1,choice,1#translation|1<translations} {0} {1,choice,1#is|1<are} checked, which will not be used within the package configuration",
            l_translationusing, l_translationusing.size()), !l_translationusing.isEmpty());
}