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:org.ado.musicdroid.service.MediaConverterService.java

@Override
protected Task<File> createTask() {
    return new Task<File>() {
        private final List<String> albumCoverProcessedList = new ArrayList<>();

        @Override/*from  w w  w .j a  v  a 2  s.c  om*/
        protected File call() throws Exception {
            for (final File songFile : songFiles) {
                updateValue(songFile);
                copyAlbumCoverIfNeeded(songFile);
                jadbDevice.push(convertSong(songFile), new RemoteFile(getRemoteLocation(songFile)));
            }
            return null;
        }

        private void copyAlbumCoverIfNeeded(File songFile) throws JadbException, IOException {
            final String albumName = getAlbumRelativePath(songFile);
            if (!albumCoverProcessedList.contains(albumName)) {
                final InputStream inputStream = Mp3Utils.getAlbumCover(songFile);
                if (inputStream != null) {
                    final File tempFile = File.createTempFile("cover", "image");
                    FileUtils.copyInputStreamToFile(inputStream, tempFile);
                    jadbDevice.push(tempFile, new RemoteFile(getAlbumCoverRemoteLocation(songFile,
                            MimeTypeMapping.getFileExtension(Mp3Utils.getAlbumCoverMimeType(songFile)))));
                }
                albumCoverProcessedList.add(albumName);
            }
        }

        private String getAlbumCoverRemoteLocation(File songFile, String fileExtension) {
            return ANDROID_MUSIC_BASE_DIRECTORY + getAlbumRelativePath(songFile) + "cover." + fileExtension;
        }

        private String getAlbumRelativePath(File songFile) {
            final String s = songFile.getAbsolutePath()
                    .substring(AppConfiguration.getConfigurationProperty("music.dir").length());
            return s.substring(0, s.lastIndexOf("/") + 1);
        }

        private File convertSong(final File songFile) throws Exception {
            final AVRootOptions options = AVRootOptions
                    .create(songFile.getAbsolutePath(), getExportDirectory(songFile))
                    .builders(AVAudioOptions.create().audioBitRate(128));
            final AVCommand command = new AVCommand().setDebug(true).setTimeout(10 * 60 * 60 * 1000L);

            LOGGER.info("Convert song [{}]", songFile.getAbsolutePath());
            final ProcessInfo processInfo = command.run(options);
            final String outputFile = options.getOutputFile();

            LOGGER.info("Output file: {}, return code: {}", outputFile, processInfo.getStatusCode());
            if (processInfo.getStatusCode() != 0) {
                LOGGER.error(processInfo.toString());
            }
            return new File(outputFile);
        }

        private String getExportDirectory(File songFile) {
            final File exportFile = new File(EXPORT_DIRECTORY, songFile.getAbsolutePath()
                    .substring(AppConfiguration.getConfigurationProperty("music.dir").length()));
            final File exportDirectory = new File(FilenameUtils.getFullPath(exportFile.getAbsolutePath()));
            if (!exportDirectory.exists()) {
                try {
                    FileUtils.forceMkdir(exportDirectory);
                } catch (IOException e) {
                    // ignore
                }
            }
            return exportFile.getAbsolutePath();
        }

        private String getRemoteLocation(File file) {
            return ANDROID_MUSIC_BASE_DIRECTORY + file.getAbsolutePath()
                    .substring(AppConfiguration.getConfigurationProperty("music.dir").length());
        }
    };
}

From source file:ninja.eivind.hotsreplayuploader.ClientTest.java

@Test
public void testJavaFXIsAvailable() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(2);
    Task<Void> javaFxTask = new Task<Void>() {
        @Override/* w w w.j a  va  2 s .  c o m*/
        protected Void call() throws Exception {
            latch.countDown();
            return null;
        }
    };
    javaFxTask.setOnSucceeded((result) -> latch.countDown());
    new Thread(javaFxTask).run();

    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("JavaFX is not available.");
    }
}

From source file:poe.trade.assist.service.AutoSearchService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {

        @Override//from  www  .ja  va2 s. c o  m
        protected Void call() throws Exception {
            int numberOfItemsFound = 0;
            for (Search search : searches) {
                String url = search.getUrl();
                if (isNotBlank(url) && search.getAutoSearch()) {
                    update(format("Downloading... %s %s", search.getName(), url));
                    String html = doDownload(url, search.getSort());
                    //                         FileUtils.writeStringToFile(new File(search.getName()), html);
                    update(format("%s for %s %s", html.isEmpty() ? "Failure" : "Success", search.getName(),
                            url));
                    search.setHtml(html);
                    search.parseHtml();
                    if (search.getResultList() != null) { // i'm not sure if list will get null, the bane of java..
                        numberOfItemsFound += search.getResultList().stream().filter(r -> r.getIsNew()).count();
                    }
                    Thread.sleep(250); // a little delay between downloads
                }
            }
            callback.accept(numberOfItemsFound);

            int mins = Math.round(60 * searchMins);

            for (int i = mins; i >= 0; i--) {
                update("Sleeping... " + i);
                Thread.sleep(1000);
            }
            return null;
        }

        private void update(String msg) {
            Platform.runLater(() -> updateMessage(msg));
        }
    };
}

From source file:Main.java

public Task createWorker() {
    return new Task() {
        @Override//w  w w  .ja  v a  2  s  .c o  m
        protected Object call() throws Exception {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(2000);
                updateMessage("2000 milliseconds");
                updateProgress(i + 1, 10);
            }
            return true;
        }
    };
}

From source file:org.mskcc.shenkers.control.track.gene.GeneModelView.java

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

        String chr = i.getChr();//from   w  w w  .j  a  v a2  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.install.InstallPresenter.java

@PostConstruct
public void init() {
    LOGGER.info("PostConstruct");
    FileUtils.deleteQuietly(TEMP_DIRECTORY);
    unzipService = new UnzipService(UPDATE_FILE, TEMP_DIRECTORY);
    unzipService.setOnRunning(event -> {
        LOGGER.info("on running");
        labelStepTwo.setText("2. Extracting update file");
    });// ww  w. j  a  v  a 2s. c o  m
    unzipService.setOnSucceeded(event -> {
        LOGGER.info("on succeeded");
        labelStepThree.setText("3. Installation process successfully finished.");

        deleteQuietly(UPDATE_FILE);
        cleanDirectory(new File(USER_DIRECTORY, "lib"));

        copyUpdateFiles(TEMP_DIRECTORY, USER_DIRECTORY);
        deleteQuietly(TEMP_DIRECTORY);

        final Task<Void> voidTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                pause(2000);
                System.exit(0);
                return null;
            }
        };
        new Thread(voidTask).start();
    });
    unzipService.setOnFailed(event -> {
        LOGGER.info("on failed");
        labelStepThree.setText("3. Error on installation process!");
        final Task<Void> voidTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                pause(2000);
                System.exit(1);
                return null;
            }
        };
        new Thread(voidTask).start();
    });
}

From source file:org.mskcc.shenkers.control.track.rest.RestIntervalView.java

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

        String chr = i.getChr();//from   ww  w.  j  a v  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:eu.over9000.skadi.service.ImportFollowedService.java

@Override
protected Task<Set<String>> createTask() {
    return new Task<Set<String>>() {

        @Override//from w w w  . j av a2s .c  o m
        protected Set<String> call() throws Exception {

            this.updateMessage("importing channels for " + ImportFollowedService.this.user);
            try {
                final Set<String> channels = new TreeSet<>();

                int limit = 0;
                int offset = 0;

                String url = "https://api.twitch.tv/kraken/users/" + ImportFollowedService.this.user
                        + "/follows/channels";
                String response = HttpUtil.getAPIResponse(url);
                JsonObject responseObject = ImportFollowedService.this.parser.parse(response).getAsJsonObject();

                String parameters = responseObject.getAsJsonObject("_links").get("self").getAsString()
                        .split("\\?")[1];
                String[] split = parameters.split("&");

                for (final String string : split) {
                    if (string.startsWith("limit")) {
                        limit = Integer.valueOf(string.split("=")[1]);
                    } else if (string.startsWith("offset")) {
                        offset = Integer.valueOf(string.split("=")[1]);
                    }
                }

                final int count = responseObject.get("_total").getAsInt();
                LOGGER.debug("total channels followed: " + count);

                this.updateProgress(count, channels.size());
                this.updateMessage("Loaded " + channels.size() + " of " + count + " channels");

                while (offset < count) {

                    ImportFollowedService.this.parseAndAddChannelsToSet(channels, responseObject);

                    url = "https://api.twitch.tv/kraken/users/" + ImportFollowedService.this.user
                            + "/follows/channels?limit=" + limit + "&offset=" + (offset + limit);
                    response = HttpUtil.getAPIResponse(url);
                    responseObject = ImportFollowedService.this.parser.parse(response).getAsJsonObject();

                    parameters = responseObject.getAsJsonObject("_links").get("self").getAsString()
                            .split("\\?")[1];
                    split = parameters.split("&");
                    for (final String string : split) {
                        if (string.startsWith("limit")) {
                            limit = Integer.valueOf(string.split("=")[1]);
                        } else if (string.startsWith("offset")) {
                            offset = Integer.valueOf(string.split("=")[1]);
                        }
                    }

                    LOGGER.debug("limit=" + limit + " offset=" + offset + " channelsize=" + channels.size());

                    this.updateProgress(count, channels.size());
                    this.updateMessage("Loaded " + channels.size() + " of " + count + " channels");
                }

                return channels;

            } catch (final HttpResponseException e) {
                if (e.getStatusCode() == 404) {
                    this.updateMessage("The given user does not exist");
                    return null;
                }

                this.updateMessage("Error: " + e.getMessage());
                LOGGER.error("Error", e);
                return null;
            } catch (final Exception e) {
                this.updateMessage("Error: " + e.getMessage());
                LOGGER.error("Error", e);
                return null;
            }
        }
    };
}

From source file:ninja.eivind.hotsreplayuploader.window.HomeController.java

private void checkNewVersion() {
    final Task<Optional<GitHubRelease>> task = new Task<Optional<GitHubRelease>>() {
        @Override//from  ww  w.j a  v  a  2s. c om
        protected Optional<GitHubRelease> call() throws Exception {
            return releaseManager.getNewerVersionIfAny();
        }
    };
    task.setOnSucceeded(event -> task.getValue().ifPresent(this::displayUpdateMessage));
    new Thread(task).start();
}

From source file:com.github.naoghuman.testdata.abclist.service.ExerciseTermService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {//from  w ww . java2s.c  o  m
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.getDefault().deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final ObservableList<Topic> topics = SqlProvider.getDefault().findAllTopics();
            final ObservableList<Term> terms = SqlProvider.getDefault().findAllTerms();
            final int sizeTerms = terms.size();
            final AtomicInteger index = new AtomicInteger(0);

            final CrudService crudService = DatabaseFacade.getDefault().getCrudService(entityName);
            final AtomicLong id = new AtomicLong(
                    -1_000_000_000L + DatabaseFacade.getDefault().getCrudService().count(entityName));
            topics.stream().forEach(topic -> {
                final ObservableList<Exercise> exercises = SqlProvider.getDefault()
                        .findAllExercisesWithTopicId(topic.getId());
                exercises.stream().filter(exercise -> exercise.isReady()).forEach(exercise -> {
                    final int maxExerciseTerms = TestdataGenerator.RANDOM.nextInt(70) + 10;
                    for (int i = 0; i < maxExerciseTerms; i++) {
                        final Term term = terms.get(TestdataGenerator.RANDOM.nextInt(sizeTerms));
                        final ExerciseTerm exerciseTerm = ModelProvider.getDefault().getExerciseTerm();
                        exerciseTerm.setExerciseId(exercise.getId());
                        exerciseTerm.setId(id.getAndIncrement());
                        exerciseTerm.setTermId(term.getId());

                        crudService.create(exerciseTerm);
                    }
                });

                updateProgress(index.getAndIncrement(), saveMaxEntities);
            });

            LoggerFacade.getDefault().deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.getDefault().debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " ExerciseTerms."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}