javafx.concurrent.Task Java Examples

The following examples show how to use javafx.concurrent.Task. 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: OeeApplication.java    From OEE-Designer with MIT License 6 votes vote down vote up
@Override
public void start(Stage primaryStage) throws Exception {
	final Task<String> startTask = new Task<String>() {
		@Override
		protected String call() throws Exception {
			// wait for a database connection by requesting an EntityManager
			PersistenceService.instance().getEntityManager();
			return getClass().getSimpleName();
		}
	};

	// start the database connection
	new Thread(startTask).start();

	// show the dialog and show the main stage when done
	showSplash(primaryStage, startTask, () -> showMainStage(null));
}
 
Example #2
Source File: Simulator.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
/** Resets simulation. */
@FXML protected synchronized void reset() {
  Thread th = new Thread(new Task<Void>() {
    /** {@inheritDoc} */
    @Override
    public Void call() {
      mainController.clearConsole();
      history.reset();
      program.getState().reset();
      program.load();
      updateMemoryCells();
      updateCacheOrganization();
      refreshSim();
      scroll();
      Globals.PRINT = false;
      Status.EXIT.set(false);
      Status.EMPTY.set(true);
      return null;
    }
  });
  th.setDaemon(true);
  th.start();
}
 
Example #3
Source File: DownloaderApp.java    From FXTutorials with MIT License 6 votes vote down vote up
private Parent createContent() {
    VBox root = new VBox();
    root.setPrefSize(400, 600);

    TextField fieldURL = new TextField();
    root.getChildren().addAll(fieldURL);

    fieldURL.setOnAction(event -> {
        Task<Void> task = new DownloadTask(fieldURL.getText());
        ProgressBar progressBar = new ProgressBar();
        progressBar.setPrefWidth(350);
        progressBar.progressProperty().bind(task.progressProperty());
        root.getChildren().add(progressBar);

        fieldURL.clear();

        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    });

    return root;
}
 
Example #4
Source File: PktCaptureService.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@Override
protected Task<CapturedPackets> createTask() {
    return new Task<CapturedPackets>() {
        @Override
        protected CapturedPackets call() throws Exception {
            if (currentActiveMonitorId == 0) {
                return null;
            }
            try {
                return fetchCapturedPkts(currentActiveMonitorId, 10);
            } catch (PktCaptureServiceException e) {
                LOG.error("Unable to fetch pkts from monitor.", e);
                return null;
            }
        }
    };
}
 
Example #5
Source File: ClothMesh.java    From FXyzLib with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            updateTimer();
            
            IntStream.range(0, getIterations()).forEach(i->{});
            points.parallelStream().filter(p->{return points.indexOf(p) % (getDivisionsX() - 1) == 0;}).forEach(p -> {
                p.applyForce(new Point3D(5,-1,1));
            });
            for (int i = 0; i < getConstraintAccuracy(); i++) {
                points.parallelStream().forEach(WeightedPoint::solveConstraints);
            }
            points.parallelStream().forEach(p -> {
                p.applyForce(new Point3D(4.8f,1,-1));
                p.updatePhysics(deltaTime, 1);                        
            });

            return null;
        }
    };
}
 
Example #6
Source File: ChatController.java    From JavaFX-Chat with GNU General Public License v3.0 6 votes vote down vote up
public synchronized void addAsServer(Message msg) {
    Task<HBox> task = new Task<HBox>() {
        @Override
        public HBox call() throws Exception {
            BubbledLabel bl6 = new BubbledLabel();
            bl6.setText(msg.getMsg());
            bl6.setBackground(new Background(new BackgroundFill(Color.ALICEBLUE,
                    null, null)));
            HBox x = new HBox();
            bl6.setBubbleSpec(BubbleSpec.FACE_BOTTOM);
            x.setAlignment(Pos.CENTER);
            x.getChildren().addAll(bl6);
            return x;
        }
    };
    task.setOnSucceeded(event -> {
        chatPane.getItems().add(task.getValue());
    });

    Thread t = new Thread(task);
    t.setDaemon(true);
    t.start();
}
 
Example #7
Source File: ThreadService.java    From AsciidocFX with Apache License 2.0 6 votes vote down vote up
public <T> Future<?> runTaskLater(Runnable runnable) {

        Task<T> task = new Task<T>() {
            @Override
            protected T call() throws Exception {
                runnable.run();
                return null;
            }
        };

        task.exceptionProperty().addListener((observable, oldValue, newValue) -> {
            if (Objects.nonNull(newValue)) {
                newValue.printStackTrace();
            }
        });

        return threadPollWorker.submit(task);
    }
 
Example #8
Source File: SearchController.java    From tutorials with MIT License 6 votes vote down vote up
private void loadData() {

        String searchText = searchField.getText();

        Task<ObservableList<Person>> task = new Task<ObservableList<Person>>() {
            @Override
            protected ObservableList<Person> call() throws Exception {
                updateMessage("Loading data");
                return FXCollections.observableArrayList(masterData
                        .stream()
                        .filter(value -> value.getName().toLowerCase().contains(searchText))
                        .collect(Collectors.toList()));
            }
        };

        task.setOnSucceeded(event -> {
            masterData = task.getValue();
            pagination.setVisible(true);
            pagination.setPageCount(masterData.size() / PAGE_ITEMS_COUNT);
        });

        Thread th = new Thread(task);
        th.setDaemon(true);
        th.start();
    }
 
Example #9
Source File: WeiboSnapRunController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
protected void saveHtml(final String filename, final String contents) {
    if (filename == null || contents == null) {
        return;
    }
    Task<Void> saveHtmlTask = new Task<Void>() {
        @Override
        protected Void call() {
            try {
                try ( BufferedWriter out = new BufferedWriter(new FileWriter(filename, Charset.forName("utf-8"), false))) {
                    out.write(contents);
                    out.flush();
                    savedHtmlCount++;
                }
            } catch (Exception e) {
                loadFailed = true;
                errorString = e.toString();
            }
            return null;
        }
    };
    new Thread(saveHtmlTask).start();
}
 
Example #10
Source File: OpcUaTrendController.java    From OEE-Designer with MIT License 6 votes vote down vote up
@Override
protected Task<String> createTask() {
	return new Task<String>() {

		@Override
		protected String call() throws Exception {
			String errorMessage = NO_ERROR;

			try {
				// resolve the input value into a reason
				Object javaValue = UaOpcClient.getJavaObject(dataValue.getValue());
				DateTime dt = dataValue.getServerTime();
				OffsetDateTime odt = DomainUtils.localTimeFromDateTime(dt);

				trendChartController.invokeResolver(getApp().getAppContext(), javaValue, odt, null);
			} catch (Exception e) {
				errorMessage = e.getMessage();

				if (errorMessage == null) {
					errorMessage = getClass().getSimpleName();
				}
			}
			return errorMessage;
		}
	};
}
 
Example #11
Source File: HttpTrendController.java    From OEE-Designer with MIT License 6 votes vote down vote up
@Override
protected Task<Void> createTask() {
	return new Task<Void>() {

		@Override
		protected Void call() {
			try {
				trendChartController.invokeResolver(getApp().getAppContext(), dataValue, timestamp, reason);
			} catch (Exception e) {
				Platform.runLater(() -> {
					AppUtils.showErrorDialog(e);
				});
			}
			return null;
		}
	};
}
 
Example #12
Source File: MainAction.java    From DevToolBox with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void pageSizeBoxChangeForValueAction() {
    try {
        DialogUtil.showDialog(mc.pane.getScene().getWindow());
        new Thread(new Task() {
            @Override
            protected Object call() throws Exception {
                mc.paginationForValue.getPageFactory().call(0);
                DialogUtil.close();
                return null;
            }

            @Override
            protected void setException(Throwable t) {
                super.setException(t);
                LOGGER.error("获取redis分页数据异常", t);
                Toast.makeText("获取redis信息异常" + t.getLocalizedMessage()).show(mc.pane.getScene().getWindow());
                DialogUtil.close();
            }
        }).start();
    } catch (Exception ex) {
        Toast.makeText("获取redis信息异常" + ex.getLocalizedMessage()).show(mc.pane.getScene().getWindow());
        LOGGER.error("获取redis信息异常", ex);
        DialogUtil.close();
    }
}
 
Example #13
Source File: AppUtils.java    From java-ml-projects with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Perform an async call
 * 
 * @param action
 * @param success
 * @param error
 */
public static <T extends Object> void doAsyncWork(Supplier<T> action, Consumer<T> success,
		Consumer<Throwable> error) {
	Task<T> tarefaCargaPg = new Task<T>() {
		@Override
		protected T call() throws Exception {
			return action.get();
		}

		@Override
		protected void succeeded() {
			success.accept(getValue());
		}

		@Override
		protected void failed() {
			error.accept(getException());
		}
	};
	Thread t = new Thread(tarefaCargaPg);
	t.setDaemon(true);
	t.start();
}
 
Example #14
Source File: PGIDStatsService.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
@Override
protected Task<PGIdStatsRPCResult> createTask() {
    return new Task<PGIdStatsRPCResult>() {
        @Override
        protected PGIdStatsRPCResult call() {
            // TODO: remove when ConnectionManager.isConnected will be returns valid result
            if (ConnectionManager.getInstance().getApiH() == null) {
                return null;
            }

            PGIdStatsRPCResult pgIDStats = null;
            try {
                synchronized (lock) {
                    pgIDStats = RPCCommands.getPGIdStats(new ArrayList<>(pgIDs));
                }
            } catch (Exception exc) {
                LOG.error("Failed to get PGID stats", exc);
            }

            return pgIDStats;
        }
    };
}
 
Example #15
Source File: AsyncImageProperty.java    From neural-style-gui with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Task<Image> createTask() {
    final File imageFile = this.imageFile;
    final int width = this.width;
    final int height = this.height;
    return new Task<Image>() {
        @Override
        protected Image call() {
            try {
                return new Image(new FileInputStream(imageFile), width, height, true, false);
            } catch (IOException e) {
                log.log(Level.SEVERE, e.toString(), e);
                return null;
            }
        }
    };
}
 
Example #16
Source File: TrainingView.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TrainingView() {

        label = new Label();

        Button button = new Button("train network model");
        button.setOnAction(e -> {
            Task task = train();
            button.disableProperty().bind(task.runningProperty());
        });
        series = new Series();
        series.setName("#iterations");
        Chart chart = createChart(series);

        VBox controls = new VBox(15.0, label, button, chart);
        controls.setAlignment(Pos.CENTER);

        setCenter(controls);
    }
 
Example #17
Source File: IntervalTree4Matches.java    From megan-ce with GNU General Public License v3.0 6 votes vote down vote up
/**
 * selects the matches to keep for a given read and puts them into an interval tree
 *
 * @param readBlock
 * @param task      can be null
 * @param progress
 * @return interval tree
 */
public static IntervalTree<IMatchBlock> computeIntervalTree(IReadBlock readBlock, Task task, ProgressListener progress) throws CanceledException {
    final IntervalTree<IMatchBlock> intervalTree = new IntervalTree<>();

    if (progress != null) {
        progress.setMaximum(readBlock.getNumberOfAvailableMatchBlocks());
        progress.setProgress(0);
    }

    for (int m = 0; m < readBlock.getNumberOfAvailableMatchBlocks(); m++) {
        final IMatchBlock matchBlock = readBlock.getMatchBlock(m);
        intervalTree.add(new Interval<>(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd(), matchBlock));
        if (task != null && task.isCancelled())
            break;
        if (progress != null)
            progress.incrementProgress();
    }
    return intervalTree;
}
 
Example #18
Source File: OpcDaTrendController.java    From OEE-Designer with MIT License 6 votes vote down vote up
@Override
protected Task<String> createTask() {
	return new Task<String>() {

		@Override
		protected String call() throws Exception {
			String errorMessage = NO_ERROR;

			try {
				// resolve the input value into a reason
				OpcDaVariant varientValue = item.getValue();
				Object value = varientValue.getValueAsObject();

				trendChartController.invokeResolver(getApp().getAppContext(), value, item.getLocalTimestamp(),
						null);
			} catch (Exception e) {
				errorMessage = e.getMessage();
			}
			return errorMessage;
		}
	};
}
 
Example #19
Source File: Player.java    From gramophy with GNU General Public License v3.0 5 votes vote down vote up
private void startUpdating()
{
    updaterThread = new Thread(new Task<Void>() {
        @Override
        protected Void call(){
            try
            {
                while(isActive)
                {
                    if(mediaPlayer.getStatus().equals(MediaPlayer.Status.PLAYING))
                    {
                        double currSec = mediaPlayer.getCurrentTime().toSeconds();
                        String currentSimpleTimeStamp = dash.getSecondsToSimpleString(currSec);
                        Platform.runLater(()->dash.nowDurLabel.setText(currentSimpleTimeStamp));

                        double currentProgress = (currSec/totalCurr)*100;
                        if(!dash.songSeek.isValueChanging())
                        {
                            dash.songSeek.setValue(currentProgress);
                            //dash.refreshSlider(dash.songSeek);
                            currentP = currentProgress;
                        }
                    }
                    Thread.sleep(500);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    });
    updaterThread.start();
}
 
Example #20
Source File: RatingScreenController.java    From SmartCity-ParkingManagement with Apache License 2.0 5 votes vote down vote up
private void getUserIdAndOrder(){
	statusLabel.setText("Loading...");
	statusLabel.setVisible(true);
	Task<Void> getUserDetailsTask = new Task<Void>() {
           @Override
           protected Void call() throws Exception {	
           	while(userId == null){
           		
           	}
           	while(parkingOrder == null){
           		
           	}
           	return null;
        }
       };
      new Thread(getUserDetailsTask).start();
      
      progressIndicator.progressProperty().bind(getUserDetailsTask.progressProperty());
      progressIndicator.setVisible(true); 
      
      getUserDetailsTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent workerStateEvent) {
       	   headerLabel.setText("Please rate the quality of your last parking experience at " + parkingOrder.getParkingSlotId() + ".");
       	   submitButton.setDisable(false);
       	   progressIndicator.setVisible(false);
       	   statusLabel.setVisible(false);
          }
      });
}
 
Example #21
Source File: LoadingController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public void init(final Task<?> task) {
    try {
        infoLabel.setText(message("Handling..."));
        infoLabel.requestFocus();
        loadingTask = task;
        isCanceled = false;
        progressIndicator.setProgress(-1F);
        if (timeLabel != null) {
            showTimer();
        }
        getMyStage().toFront();
    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #22
Source File: CodeAreaConfigurator.java    From kafka-message-tool with MIT License 5 votes vote down vote up
private static Task<StyleSpans<Collection<String>>> computeHighlightingAsync(CodeArea codeArea,
                                                                             Pattern pattern,
                                                                             Function<Matcher, String> getStyleClassFunction,
                                                                             Executor executor) {
    String text = codeArea.getText();
    Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {
        @Override
        protected StyleSpans<Collection<String>> call() throws Exception {
            return computeHighlighting(text, pattern, getStyleClassFunction);
        }
    };
    executor.execute(task);
    return task;
}
 
Example #23
Source File: GuiController.java    From Recaf with MIT License 5 votes vote down vote up
/**
 * @param path
 * 		Path to workspace file to open.
 *
 * @return Task to load the given workspace,
 * which yields {@code true} if the workspace was loaded successfully.
 */
private Task<Boolean> loadWorkspace(Path path) {
	return new Task<Boolean>() {
		@Override
		protected Boolean call() throws Exception {
			LoadWorkspace loader = new LoadWorkspace();
			loader.input = path;
			try {
				// This ugly garbage handles updating the UI with the progress message
				// and how long that message has been shown for in seconds/millis
				long updateInterval = 16;
				long start = System.currentTimeMillis();
				ScheduledFuture<?> future = ThreadUtil.runRepeated(updateInterval, () -> {
					long time = System.currentTimeMillis() - start;
					updateMessage(loader.getStatus() +
							String.format("\n- Elapsed: %02d.%02d", time / 1000, (time % 1000)));
				});
				// Start the load process
				setWorkspace(loader.call());
				windows.getMainWindow().clearTabViewports();
				config().backend().onLoad(path);
				// Stop message updates
				future.cancel(true);
				return true;
			} catch(Exception ex) {
				error(ex, "Failed to open file: {}", path.getFileName());
				ExceptionAlert.show(ex, "Failed to open file: " + path.getFileName());
				return false;
			}
		}
	};
}
 
Example #24
Source File: MainWindowController.java    From SmartModInserter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void updateGlobalProgress(boolean force) {
    if (force || System.currentTimeMillis() - lastGlobalProgressUpdate > 100) {
        int runningTasks = 0;
        int tasksWaiting = 0;
        double progress = 0;
        for (Task task : TaskService.getInstance().getTasks()) {
            if (task.isRunning()) {
                runningTasks ++;
                if (task.getWorkDone() >= 0) {
                    progress += task.getProgress();
                } else {
                    tasksWaiting ++;
                }
            }
        }
        double length;
        if (tasksWaiting == runningTasks || runningTasks == 0) {
            length = 360;
        } else {
            length = 360d * (progress / (double) runningTasks);
        }

        globalProgress.setLength(length);

        lastGlobalProgressUpdate = System.currentTimeMillis();
    }
}
 
Example #25
Source File: ProgressPaneController.java    From CMPDL with MIT License 5 votes vote down vote up
private void bind(Task<?> task, Label subLabel, ProgressBar progressBar, ProgressIndicator progressIndicator) {
    if (task != null) {
        subLabel.textProperty().bind(task.titleProperty());
        progressBar.progressProperty().bind(task.progressProperty());
        progressIndicator.progressProperty().bind(task.progressProperty());
    } else {
        subLabel.textProperty().unbind();
        subLabel.setText("");
        progressBar.progressProperty().unbind();
        progressBar.setProgress(0);
        progressIndicator.progressProperty().unbind();
        progressIndicator.setProgress(0);
    }
}
 
Example #26
Source File: Controller.java    From everywhere with Apache License 2.0 5 votes vote down vote up
public void runIndex(ActionEvent e) {
    Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            executeIndex();
            return null;
        }
    };
    task.setOnSucceeded(event -> {
        tabPanel.getSelectionModel().select(0);
        indexLabel.setText("index finished!");
    });
    new Thread(task).start();
}
 
Example #27
Source File: AuditLogTaskRecord.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public AuditLogTaskRecord(@Nonnull Task<?> task) {
  this.taskMessage = task.getMessage();
  this.taskTitle = task.getTitle();

  task.stateProperty().addListener(new ChangeListener<State>() {
    public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
      taskStatus = newState;
    }
  });

}
 
Example #28
Source File: MidiHandler.java    From EWItool with GNU General Public License v3.0 5 votes vote down vote up
MidiHandler( SharedData pSharedData, UserPrefs pUserPrefs ) {

    sharedData = pSharedData;
    userPrefs = pUserPrefs;
    ignoreEvents = false;
    
    /** 
     * This task was introduced to work around a hang on OS X in
     * the CoreMidi4J v0.4 MidiSystem.getMidiDeviceInfo() call which 
     * seems to encounter a resource lock if run on the main thread.
     */
    Task<Void> mt = new Task<Void>() {
      @Override
      protected Void call() throws Exception {
        scanAndOpenMIDIPorts();
        return null;
      }
    };
    new Thread( mt ).start();

    
    // This was unsafe w.r.t. other MIDI messages that may be in-flight.
    // If it is to be reintroduced at any point then it should probably wait for 
    // MIDI idle and somehow LOCK other MIDI traffic before each query
//    Task<Void> checkerTask = new Task<Void>() {
//      @Override
//      protected Void call() throws Exception {
//        while (true) {
//          if (inDev != null && outDev != null) {
//            if (inDev.isOpen() && outDev.isOpen()) {
//              Platform.runLater( () -> requestDeviceID() );
//            }
//          }
//          Thread.sleep( 15000 ); // 15s
//        }
//      }
//    };
//    new Thread( checkerTask ).start();
  }
 
Example #29
Source File: AuditLogExportModule.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
    @Nonnull Collection<Task<?>> tasks) {

  // final File outputFile = parameters
  // .getParameter(AuditLogExportParameters.outputFile).getValue();

  // List of modules which won't be shown in the audit log
  final List<MZmineModule> removeModules = new ArrayList<>();
  removeModules.add(MZmineCore.getModuleInstance(AuditLogExportModule.class));
  removeModules.add(MZmineCore.getModuleInstance(CsvExportModule.class));

  // Loop through all entries in the audit log
  List<AuditLogEntry> auditLog = MZmineCore.getCurrentProject().getAuditLog();
  for (AuditLogEntry logEntry : auditLog) {

    // Don't show modules from the remove list
    if (!removeModules.contains(logEntry.getModule())) {
      // String moduleName = logEntry.getModule().getName();

      /*
       * TODO
       */
      for (Parameter<?> pramaeter : logEntry.getParameterSet()) {
        logger.debug(pramaeter.getName() + ": " + pramaeter.getValue());
      }
    }

  }

}
 
Example #30
Source File: UploadContentService.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            if (MainApp.getZdsutils().isAuthenticated() && result.isPresent()) {
                String targetId = result.get().getValue().getId();
                String targetSlug = result.get().getValue().getSlug();

                String pathDir = content.getFilePath ();
                updateMessage(Configuration.getBundle().getString("ui.task.zip.label")+" : "+targetSlug+" "+Configuration.getBundle().getString("ui.task.pending.label")+" ...");
                ZipUtil.pack(new File(pathDir), new File(pathDir + ".zip"));
                updateMessage(Configuration.getBundle().getString("ui.task.import.label")+" : "+targetSlug+" "+Configuration.getBundle().getString("ui.task.pending.label")+" ...");
                if(result.get().getValue().getType() == null) {
                    if(!MainApp.getZdsutils().importNewContent(pathDir+ ".zip", result.get().getKey())) {
                        throw new IOException();
                    }
                } else {
                    if(!MainApp.getZdsutils().importContent(pathDir + ".zip", targetId, targetSlug, result.get().getKey())) {
                        throw new IOException();
                    }
                }

                updateMessage(Configuration.getBundle().getString("ui.task.content.sync")+" ...");
                try {
                    MainApp.getZdsutils().getContentListOnline().clear();
                    MainApp.getZdsutils().initInfoOnlineContent("tutorial");
                    MainApp.getZdsutils().initInfoOnlineContent("article");
                } catch (IOException e) {
                    logger.error("Echec de téléchargement des metadonnés des contenus en ligne", e);
                }
            }
            return null;
        }
    };
}