Java Code Examples for javafx.concurrent.Task#setOnFailed()

The following examples show how to use javafx.concurrent.Task#setOnFailed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UIUtils.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Run a task with process dialog
 */
public static <T> void runTaskWithProcessDialog(Task<T> task, String failedMessage) {
    var progressDialog = new ProgressDialog();
    progressDialog.bindTask(task);

    task.setOnSucceeded(e -> Platform.runLater(progressDialog::close));
    task.setOnFailed(e -> {
        Platform.runLater(progressDialog::close);
        Throwable throwable = task.getException();
        logger.error(failedMessage, throwable);
        UIUtils.showMessageDialog(failedMessage + ": " + throwable.getMessage());
    });

    Thread thread = new Thread(task);
    thread.start();
    progressDialog.show();
}
 
Example 2
Source File: URLContentCacheBase.java    From TweetwallFX with MIT License 6 votes vote down vote up
/**
 * Retrieves the cached content asyncronuously for {code urlString} and
 * passes it to {@code contentConsumer}. If no cached content exists the
 * content loaded and cached and then passed to {@code contentConsumer}.
 *
 * @param urlString the string of the URL content to get
 *
 * @param contentConsumer the Consumer processing the content
 */
public final void getCachedOrLoad(final String urlString, final Consumer<URLContent> contentConsumer) {
    Objects.requireNonNull(contentConsumer, "contentConsumer must not be null");
    final Task<URLContent> task = new Task<URLContent>() {

        @Override
        protected URLContent call() throws Exception {
            return getCachedOrLoadSync(urlString);
        }
    };

    task.setOnSucceeded(event
            -> contentConsumer.accept(task.getValue()));
    task.setOnFailed(event
            -> LOG.error(MESSAGE_LOAD_FAILED, cacheName, urlString, task.getException()));
    contentLoader.execute(task);
}
 
Example 3
Source File: URLContentCacheBase.java    From TweetwallFX with MIT License 6 votes vote down vote up
private void putCachedContentAsync(final String urlString, final Consumer<URLContent> contentConsumer) {
    final Task<URLContent> task = new Task<URLContent>() {

        @Override
        protected URLContent call() throws Exception {
            return new URLContent(urlString);
        }
    };

    task.setOnSucceeded(event -> {
        putCachedContent(urlString, task.getValue());

        if (null != contentConsumer) {
            contentConsumer.accept(task.getValue());
        }
    });
    task.setOnFailed(event
            -> LOG.error(MESSAGE_LOAD_FAILED, cacheName, urlString, task.getException()));
    contentLoader.execute(task);
}
 
Example 4
Source File: SearchablePaneController.java    From Everest with Apache License 2.0 5 votes vote down vote up
private void loadInitialItemsAsync() {
    Task<List<T>> entryLoader = new Task<List<T>>() {
        @Override
        protected List<T> call() {
            return loadInitialEntries();
        }
    };

    entryLoader.setOnSucceeded(e -> {
        try {
            List<T> entries = entryLoader.get();
            if (entries.size() == 0) {
                searchPromptLayer.setVisible(true);
                return;
            }

            for (T state : entries)
                addHistoryItem(state);
        } catch (InterruptedException | ExecutionException E) {
            LoggingService.logSevere("Task thread interrupted while populating HistoryTab.", E,
                    LocalDateTime.now());
        }
    });

    entryLoader.setOnFailed(e -> LoggingService.logWarning("Failed to load history.",
            (Exception) entryLoader.getException(), LocalDateTime.now()));

    MoreExecutors.directExecutor().execute(entryLoader);
}
 
Example 5
Source File: GuiController.java    From Recaf with MIT License 5 votes vote down vote up
/**
 * Asynchronously load a workspace from the given file.
 *
 * @param path
 * 		Path to workspace file.
 * @param action
 * 		Additional action to run with success/fail result.
 */
public void loadWorkspace(Path path, Consumer<Boolean> action) {
	Task<Boolean> loadTask = loadWorkspace(path);
	MainWindow main = windows.getMainWindow();
	loadTask.messageProperty().addListener((n, o, v) -> main.status(v));
	loadTask.setOnRunning(e -> {
		// Clear current items since we want to load a new workspace
		main.clear();
		main.disable(true);
	});
	loadTask.setOnSucceeded(e -> {
		// Load success
		main.disable(false);
		if (action != null)
			action.accept(true);
		// Update recently loaded
		config().backend().onLoad(path);
		main.getMenubar().updateRecent();
		// Updated cached primary jar to support recompile
		getWorkspace().writePrimaryJarToTemp();
	});
	loadTask.setOnFailed(e -> {
		// Load failure
		main.status("Failed to open file:\n" + path.getFileName());
		main.disable(false);
		if (action != null)
			action.accept(false);
	});
	ThreadUtil.run(loadTask);
}
 
Example 6
Source File: Archivo.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
private void checkForUpdates() {
    Task<SoftwareUpdateDetails> updateCheck = new UpdateCheckTask();
    updateCheck.setOnSucceeded(event -> {
        SoftwareUpdateDetails update = updateCheck.getValue();
        if (update.isAvailable()) {
            logger.info("Update check: A newer version of {} is available!", APPLICATION_NAME);
            showUpdateDialog(update);
        } else {
            logger.info("Update check: This is the latest version of {} ({})", APPLICATION_NAME, APPLICATION_VERSION);
        }
    });
    updateCheck.setOnFailed(event -> logger.error("Error checking for updates: ", event.getSource().getException()));
    Executors.newSingleThreadExecutor().submit(updateCheck);
}
 
Example 7
Source File: Archivo.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
public void cleanShutdown() {
    if (!confirmTaskCancellation()) {
        return;
    }

    archiveHistory.save();
    saveWindowDimensions();

    int waitTimeMS = 100;
    int msLimit = 15000;
    if (archiveQueueManager.hasTasks()) {
        setStatusText("Exiting...");
        try {
            int msWaited = 0;
            archiveQueueManager.cancelAllArchiveTasks();
            while (archiveQueueManager.hasTasks() && msWaited < msLimit) {
                Thread.sleep(waitTimeMS);
                msWaited += waitTimeMS;
            }
        } catch (InterruptedException e) {
            logger.error("Interrupted while waiting for archive tasks to shutdown: ", e);
        }
    }

    boolean reportingCrashes = crashReportController.hasCrashReport() && getUserPrefs().getShareTelemetry();
    if (reportingCrashes) {
        setStatusText("Exiting...");
        Task<Void> crashReportTask = crashReportController.buildTask();
        crashReportTask.setOnSucceeded(event -> shutdown());
        crashReportTask.setOnFailed(event -> shutdown());
        Executors.newSingleThreadExecutor().submit(crashReportTask);
    } else {
        shutdown();
    }
}
 
Example 8
Source File: ResourceView.java    From sis with Apache License 2.0 4 votes vote down vote up
private void openFile(File f) {
    Task<Void> t = new Task<Void>() {
        @Override
        protected Void call() throws DataStoreException {
            MetadataOverview meta;
            DataStore ds = DataStores.open(f.getAbsolutePath());
            meta = new MetadataOverview(new DefaultMetadata(ds.getMetadata()), f.getAbsolutePath());
            return null;
        }
    };
    t.setOnSucceeded(ac -> {
        Label label = new Label(f.getName());
        label.setId(f.getAbsolutePath());
        if (labToTrv.contains(f.getAbsolutePath())) {
            for (Label elem : labelToItem.keySet()) {
                if (elem.getId().equals(f.getAbsolutePath())) {
                    Event.fireEvent(elem, new MouseEvent(MouseEvent.MOUSE_CLICKED, 0, 0, 0, 0, MouseButton.PRIMARY, 1, true, true, true, true, true, true, true, true, true, true, null));
                }
            }
        } else {
            setOnClick(label);
            TreeItem<Label> tItem = new TreeItem<>(label);
            labelToItem.put(label, tItem);
            labToTrv.add(f.getAbsolutePath());
            root.getChildren().add(tItem);
        }
    });
    t.setOnFailed(ac -> {
        final Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("An error was occur");
        Label lab = new Label(t.getException().getMessage());
        lab.setWrapText(true);
        lab.setMaxWidth(650);
        VBox vb = new VBox();
        vb.getChildren().add(lab);
        alert.getDialogPane().setContent(vb);
        alert.show();
    });
    final Thread thread = new Thread(t);
    thread.setDaemon(true);
    thread.start();
}
 
Example 9
Source File: LaTeXDraw.java    From latexdraw with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void start(final Stage stage) {
	final Task<Void> task = new Task<>() {
		@Override
		protected Void call() throws IOException {
			updateProgress(0.1, 1d);
			final CountDownLatch latch = new CountDownLatch(1);

			Platform.runLater(() -> {
				mainStage = new Stage(StageStyle.DECORATED);
				mainStage.setIconified(true);
				injector = new LatexdrawInjector(LaTeXDraw.this);
				latch.countDown();
			});

			// We need to wait for the javafx thread to perform its job before loading the UI (because of the injector).
			try {
				latch.await();
			}catch(final InterruptedException ex) {
				Thread.currentThread().interrupt();
				throw new RuntimeException(ex);
			}

			final PreferencesService prefs = injector.getInstance(PreferencesService.class);
			prefs.readPreferences();

			final Parent root = FXMLLoader.load(getClass().getResource("/fxml/UI.fxml"), prefs.getBundle(), //NON-NLS
				injector.getInstance(BuilderFactory.class), cl -> injector.getInstance(cl));
			updateProgress(0.6, 1d);
			final Scene scene = new Scene(root);
			updateProgress(0.7, 1d);
			scene.getStylesheets().add("css/style.css"); //NON-NLS
			// Binding the title of the app on the title of the drawing.
			mainStage.titleProperty().bind(injector.getInstance(Drawing.class).titleProperty().concat(" -- " + LABEL_APP));
			updateProgress(0.8, 1d);

			Platform.runLater(() -> {
				mainStage.setScene(scene);
				updateProgress(0.9, 1d);
				setModified(false);
				mainStage.show();
				registerScene(scene);
				// Preventing the stage to close automatically.
				mainStage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, WindowEvent::consume);
				mainStage.getIcons().add(new Image("/res/LaTeXDrawIcon.png")); //NON-NLS
				mainStage.centerOnScreen();
				injector.getInstance(TabSelector.class).centreViewport();
				injector.getInstance(Canvas.class).requestFocus();
				// Checking a new version if required.
				if(VersionChecker.WITH_UPDATE && injector.getInstance(PreferencesSetter.class).isVersionCheckEnable()) {
					new Thread(new VersionChecker(injector.getInstance(StatusBarController.class), prefs.getBundle())).start();
				}
				setModified(false);
			});
			return null;
		}
	};

	task.setOnFailed(BadaboomCollector.INSTANCE);
	showSplash(stage, task);
	new Thread(task).start();
}