Example usage for javafx.concurrent Task Task

List of usage examples for javafx.concurrent Task Task

Introduction

In this page you can find the example usage for javafx.concurrent Task Task.

Prototype

public Task() 

Source Link

Document

Creates a new Task.

Usage

From source file:ninja.javafx.smartcsv.fx.util.SaveFileService.java

@Override
protected Task createTask() {
    return new Task() {
        @Override//from  w w w .ja  v  a2 s.c o m
        protected Void call() throws Exception {
            try {
                file.save();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
            return null;
        }
    };
}

From source file:herudi.controller.controllSplash.java

private void longStart() {
    Service<ApplicationContext> service = new Service<ApplicationContext>() {
        @Override/*w ww .j  ava2 s .  c  o  m*/
        protected Task<ApplicationContext> createTask() {
            return new Task<ApplicationContext>() {
                @Override
                protected ApplicationContext call() throws Exception {
                    ApplicationContext appContex = config.getInstance().getApplicationContext();
                    int max = appContex.getBeanDefinitionCount();
                    updateProgress(0, max);
                    for (int k = 0; k < max; k++) {
                        Thread.sleep(50);
                        updateProgress(k + 1, max);
                    }
                    return appContex;
                }
            };
        }
    };
    service.start();
    service.setOnRunning((WorkerStateEvent event) -> {
        new FadeInLeftTransition(lblWelcome).play();
        new FadeInRightTransition(lblRudy).play();
        new FadeInTransition(vboxBottom).play();
    });
    service.setOnSucceeded((WorkerStateEvent event) -> {
        config2 config = new config2();
        config.newStage(stage, lblClose, "/herudi/view/login.fxml", "Sample Apps", true, StageStyle.UNDECORATED,
                false);
    });
}

From source file:com.thomaskuenneth.openweathermapweather.FXMLDocumentController.java

@FXML
void handleButtonAction(ActionEvent event) {
    Task<Void> t = new Task<Void>() {

        @Override//from   w  ww.j  a v  a  2 s  .  c  om
        protected Void call() throws Exception {
            try {
                final WeatherData weather = WeatherUtils.getWeather(city.getText());
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        Image i = new Image("http://openweathermap.org/img/w/" + weather.icon + ".png");
                        image.setImage(i);
                        beschreibung.setText(weather.description);
                        Double temp = weather.temp - 273.15;
                        temperatur.setText(MessageFormat.format("{0} \u2103", temp.intValue()));
                    }

                });
            } catch (JSONException | IOException ex) {
                LOGGER.log(Level.SEVERE, "handleButtonAction()", ex);
            }
            return null;
        }
    };
    new Thread(t).start();
}

From source file:org.mskcc.shenkers.control.track.bam.BamView2.java

@Override
public Task<Pane> getContent(BamContext context) {
    return context.spanProperty().getValue().map(i -> {

        String chr = i.getChr();/*from www .jav a 2  s .  c  o  m*/
        int start = i.getStart();
        int end = i.getEnd();

        Task<Pane> task = new PaneTask(context, chr, start, end);

        logger.info("returning task");
        return task;
    }).orElse(new Task<Pane>() {

        @Override
        protected Pane call() throws Exception {
            return new BorderPane(new Label("coordinates not set"));
        }
    }
    //                new BorderPane(new Label("bamview1: span not set"))
    //                new Pane()
    );
}

From source file:org.ado.biblio.desktop.server.ServerStatusService.java

@Override
protected Task<ServerStatusEnum> createTask() {
    return new Task<ServerStatusEnum>() {
        @Override//from  w  ww .j  ava  2s .c o  m
        protected ServerStatusEnum call() throws Exception {
            final String requestUrl = String.format(SERVER_URL,
                    AppConfiguration.getConfigurationProperty("server.url"), "status");
            try {
                HttpClient client = HttpClientBuilder.create().build();
                HttpGet request = new HttpGet(requestUrl);
                HttpResponse response = client.execute(request);

                LOGGER.info("Response code [{}]", response.getStatusLine().getStatusCode());
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    return ServerStatusEnum.OFFLINE;
                }
                return getServerStatus(IOUtils.toString(response.getEntity().getContent()));
            } catch (IOException | IllegalStateException e) {
                return ServerStatusEnum.OFFLINE;
            }
        }

        private ServerStatusEnum getServerStatus(String responseContent) {
            return new Gson().fromJson(responseContent, ServerStatusMessage.class).getServerStatusEnum();
        }
    };
}

From source file:com.toyota.carservice.controller.SplashController.java

private void longStart() {
    Service<ApplicationContext> service = new Service<ApplicationContext>() {
        @Override// ww w . j  a va 2s .c  om
        protected Task<ApplicationContext> createTask() {
            return new Task<ApplicationContext>() {
                @Override
                protected ApplicationContext call() throws Exception {
                    ApplicationContext appContex = config.getInstance().getApplicationContext();
                    int max = appContex.getBeanDefinitionCount();
                    updateProgress(0, max);
                    System.out.println(PathUtil.getRootPath());
                    File file = new File(PathUtil.getRootPath());

                    if (!file.exists()) {
                        file.mkdir();
                    }

                    if (max < 50) {
                        max = 50;
                    }
                    for (int k = 0; k < max; k++) {
                        Thread.sleep(50);
                        updateProgress(k + 1, max);
                    }
                    return appContex;
                }
            };
        }
    };
    service.start();
    service.setOnRunning((WorkerStateEvent event) -> {
        new FadeInLeftTransition(lblWelcome).play();
        new FadeInRightTransition(lblRudy).play();
        new FadeInTransition(vboxBottom).play();
    });
    service.setOnSucceeded((WorkerStateEvent event) -> {
        config2 config = new config2();
        config.newStage(stage, lblClose, "/com/toyota/carservice/view/formSwitchMode.fxml",
                "Aplikasi Informasi Service", true, StageStyle.UNDECORATED, false);
    });
}

From source file:org.ado.biblio.desktop.server.ServerPullingService.java

@Override
protected Task<BookMessageDTO[]> createTask() {

    return new Task<BookMessageDTO[]>() {
        @Override/*from   www . ja va  2  s . co  m*/
        protected BookMessageDTO[] call() throws Exception {

            final String requestUrl = String.format(SERVER_PULL_URL,
                    AppConfiguration.getConfigurationProperty("server.url"), clientId);

            try {
                HttpClient client = HttpClientBuilder.create().build();
                HttpGet request = new HttpGet(requestUrl);
                HttpResponse response = client.execute(request);

                LOGGER.info("Response code [{}]", response.getStatusLine().getStatusCode());

                String responseContent = IOUtils.toString(response.getEntity().getContent());
                final BookMessageDTO[] bookMessageDTOs = new Gson().fromJson(responseContent,
                        BookMessageDTO[].class);
                return bookMessageDTOs;

            } catch (Exception e) {
                LOGGER.error(String.format("Unable to pull server %s", requestUrl), e);
                pause(15);
                throw e;
            }
        }
    };
}

From source file:org.mskcc.shenkers.control.track.bigwig.BigWigView.java

@Override
public Task<Pane> getContent(BigWigContext context) {
    return context.spanProperty().getValue().map(i -> {

        String chr = i.getChr();//from w  ww  .ja  v a2 s. co  m
        int start = i.getStart();
        int end = i.getEnd();

        Task<Pane> task = new PaneTask(context, chr, start, end);

        logger.info("returning task");
        return task;
    }).orElse(new Task<Pane>() {

        @Override
        protected Pane call() throws Exception {
            return new BorderPane(new Label("coordinates not set"));
        }
    }
    //                new BorderPane(new Label("bamview1: span not set"))
    //                new Pane()
    );
}

From source file:eu.over9000.skadi.service.DownloadService.java

@Override
protected Task<File> createTask() {
    return new Task<File>() {
        protected File call() throws Exception {
            LOGGER.info(String.format("Downloading file %s to %s", DownloadService.this.remoteUrl,
                    DownloadService.this.localFile.getAbsolutePath()));

            HttpGet httpGet = new HttpGet(DownloadService.this.remoteUrl);
            HttpResponse response = DownloadService.this.httpClient.execute(httpGet);
            OutputStream localFileStream = null;

            try (InputStream remoteContentStream = response.getEntity().getContent()) {
                long fileSize = response.getEntity().getContentLength();
                LOGGER.debug(String.format("Size of file to download is %s", fileSize));

                localFileStream = new FileOutputStream(DownloadService.this.localFile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int sizeOfChunk;
                int amountComplete = 0;
                long startTime = System.nanoTime();
                while ((sizeOfChunk = remoteContentStream.read(buffer)) != -1) {
                    if (this.isCancelled()) {
                        this.updateMessage("Download cancelled");
                        return null;
                    }/*w  w w. java 2  s .  c o  m*/

                    localFileStream.write(buffer, 0, sizeOfChunk);

                    amountComplete += sizeOfChunk;
                    this.updateProgress(amountComplete, fileSize);

                    long bytesec = (long) ((double) amountComplete / (System.nanoTime() - startTime)
                            * NANOS_IN_SECOND);

                    this.updateMessage(String.format("Downloaded %s of %s kB (%d%% @%s/s)",
                            FileUtils.byteCountToDisplaySize(amountComplete),
                            FileUtils.byteCountToDisplaySize(fileSize),
                            (int) ((double) amountComplete / (double) fileSize * 100.0),
                            FileUtils.byteCountToDisplaySize(bytesec)));

                }
                this.updateMessage("Download completed");
                return DownloadService.this.localFile;
            } finally {
                if (localFileStream != null) {
                    localFileStream.close();
                }
            }
        }
    };
}

From source file:com.thomaskuenneth.openweathermapweather.BasicView.java

private void doIt() {
    Task<Void> t = new Task<Void>() {
        @Override//from w  w  w  .  j  av a 2s .  c  om
        protected Void call() throws Exception {
            try {
                final WeatherData weather = WeatherUtils.getWeather(city.getText());
                Platform.runLater(() -> {
                    Image i = new Image("http://openweathermap.org/img/w/" + weather.icon + ".png");
                    image.setImage(i);
                    beschreibung.setText(weather.description);
                    Double temp = weather.temp - 273.15;
                    temperatur.setText(MessageFormat.format("{0} \u2103", temp.intValue()));
                });
            } catch (JSONException | IOException ex) {
                LOGGER.log(Level.SEVERE, "handleButtonAction()", ex);
            }
            return null;
        }
    };
    new Thread(t).start();
}