List of usage examples for javafx.concurrent Task messageProperty
@Override public final ReadOnlyStringProperty messageProperty()
From source file:employees.Employees.java
@Override public void start(Stage stage) throws Exception { // Parent root = FXMLLoader.load(getClass().getResource("MainUI.fxml")); // /* w w w .j a v a 2 s. co m*/ // Scene scene = new Scene(root); // // stage.setScene(scene); // stage.show(); //new LoginStage(); Task<String> inittask = inittasks.pingServer(); StringProperty pingResponse = new SimpleStringProperty(); StringProperty messages = new SimpleStringProperty(); pingResponse.bind(inittask.valueProperty()); messages.bind(inittask.messageProperty()); inittask.stateProperty().addListener((workerState, oldState, newState) -> { if (newState == Worker.State.SUCCEEDED) { String response = pingResponse.get(); JSONObject obj = new JSONObject(response); String Status = obj.getString("Status"); if (Status.equals("OK")) { AlertDialog ad = new AlertDialog(); ad.showDialog(AlertTypes.Types.INFORMATION, "Successfull", "PING OK", "Connection Successfull"); } } else if (newState == Worker.State.CANCELLED) { AlertDialog ad = new AlertDialog(); ad.showDialog(AlertTypes.Types.WARNING, "Operation Aborted", "Operation Aborted", "Task Was Cancelled,The System Will Now Exit"); System.exit(0); } else if (newState == Worker.State.FAILED) { StringBuilder errstr = new StringBuilder(); errstr.append( "An Error Has Occured While Connecting to The Server, A Description of the Error is Shown Below : \n"); errstr.append(messages.toString()); AlertDialog ad = new AlertDialog(); ad.showDialog(AlertTypes.Types.ERROR, "An Error Occurred While Connecting to The Server", "Error", messages.get()); Optional<ButtonType> response = AlertDialog.showConfirmation( "Unable to Connect to The Server: Would you Like To Review Your Network Settings?", "Connection Settings Review", "Review Connection Settings?"); if (response.get() == ButtonType.OK) { try { new initSettingsStage(); } catch (IOException ex) { Logger.getLogger(Employees.class.getName()).log(Level.SEVERE, null, ex); } } } }); new Thread(inittask).start(); }
From source file:sh.isaac.api.util.DownloadUnzipTask.java
/** * Call.//www. ja v a 2s . c o m * * @return the file * @throws Exception the exception * @see javafx.concurrent.Task#call() */ @Override protected File call() throws Exception { final File dataFile = download(this.url); String calculatedSha1Value = null; String expectedSha1Value = null; ; try { LOG.debug("Attempting to get .sha1 file"); final File sha1File = download(new URL(this.url.toString() + ".sha1")); expectedSha1Value = Files.readAllLines(sha1File.toPath()).get(0); final Task<String> calculateTask = ChecksumGenerator.calculateChecksum("SHA1", dataFile); calculateTask.messageProperty().addListener( (ChangeListener<String>) (observable, oldValue, newValue) -> updateMessage(newValue)); calculateTask.progressProperty().addListener((ChangeListener<Number>) (observable, oldValue, newValue) -> updateProgress(calculateTask.getProgress(), calculateTask.getTotalWork())); WorkExecutors.get().getExecutor().execute(calculateTask); calculatedSha1Value = calculateTask.get(); sha1File.delete(); } catch (final Exception e1) { LOG.debug("Failed to get .sha1 file", e1); } if ((calculatedSha1Value != null) && !calculatedSha1Value.equals(expectedSha1Value)) { if (this.failOnBadCheksum) { throw new RuntimeException("Checksum of downloaded file '" + this.url.toString() + "' does not match the expected value!"); } else { LOG.warn("Checksum of downloaded file '" + this.url.toString() + "' does not match the expected value!"); } } if (this.cancel) { LOG.debug("Download cancelled"); throw new Exception("Cancelled!"); } if (this.unzip) { updateTitle("Unzipping"); try { final ZipFile zipFile = new ZipFile(dataFile); zipFile.setRunInThread(true); zipFile.extractAll(this.targetFolder.getAbsolutePath()); while (zipFile.getProgressMonitor().getState() == ProgressMonitor.STATE_BUSY) { if (this.cancel) { zipFile.getProgressMonitor().cancelAllTasks(); LOG.debug("Download cancelled"); throw new Exception("Cancelled!"); } updateProgress(zipFile.getProgressMonitor().getPercentDone(), 100); updateMessage("Unzipping " + dataFile.getName() + " at " + zipFile.getProgressMonitor().getPercentDone() + "%"); try { // TODO see if there is an API where I don't have to poll for completion Thread.sleep(25); } catch (final InterruptedException e) { // noop } } LOG.debug("Unzip complete"); } catch (final Exception e) { LOG.error("error unzipping", e); throw new Exception("The downloaded file doesn't appear to be a zip file"); } finally { dataFile.delete(); } return this.targetFolder; } else { return dataFile; } }
From source file:utilitybasedfx.MainGUIController.java
private void enableWorking(Task task) { btnImportSource.setDisable(true);//from w w w . ja v a2 s . com btnImportCompiled.setDisable(true); btnCompileFromSource.setDisable(true); btnGenerate.setDisable(true); lblWorking.setVisible(true); barWorking.setVisible(true); lblWorkingTask.setVisible(true); lblWorkingTask.textProperty().bind(task.messageProperty()); barWorking.progressProperty().bind(task.progressProperty()); task.stateProperty().addListener(new ChangeListener<Worker.State>() { @Override public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State oldState, Worker.State newState) { if (newState == Worker.State.SUCCEEDED) { disableWorking(); } else if (newState == Worker.State.FAILED) { disableWorking(); //Utils.stackErrorDialog((Exception)task.getException()); task.getException().printStackTrace(); Alert alert = new Alert(AlertType.ERROR); alert.setTitle("There was an error"); alert.setHeaderText("There was some kind of error while trying to do the current task"); alert.setContentText(task.getException().toString()); alert.showAndWait(); } } }); new Thread(task).start(); }
From source file:editeurpanovisu.EquiCubeDialogController.java
/** * *///from www . ja va2 s . c o m private void validerE2C() { if (fileLstFichier == null) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle(rbLocalisation.getString("transformation.traiteImages")); alert.setHeaderText(null); alert.setContentText(rbLocalisation.getString("transformation.traiteImagesPasFichiers")); alert.showAndWait(); } else { Alert alert = new Alert(AlertType.WARNING); alert.setTitle(rbLocalisation.getString("transformation.traiteImages")); alert.setHeaderText(null); alert.setContentText(rbLocalisation.getString("transformation.traiteImagesMessage")); alert.showAndWait(); lblTermine = new Label(); lblTermine.setText("Traitement en cours"); lblTermine.setLayoutX(24); lblTermine.setLayoutY(250); paneChoixTypeFichier.getChildren().add(lblTermine); pbBarreAvancement.setId("bar"); lblTermine.setId("lblTermine"); pbBarreAvancement.setVisible(true); pbBarreImage.setVisible(true); Task taskTraitement; taskTraitement = tskTraitement(); pbBarreAvancement.progressProperty().unbind(); pbBarreImage.setProgress(0.001); pbBarreAvancement.setProgress(0.001); pbBarreAvancement.progressProperty().bind(taskTraitement.progressProperty()); lblTermine.textProperty().unbind(); lblTermine.textProperty().bind(taskTraitement.messageProperty()); Thread thrTraitement = new Thread(taskTraitement); thrTraitement.setDaemon(true); thrTraitement.start(); } }
From source file:com.bekwam.resignator.JarsignerConfigController.java
private void loadAliases() { if (StringUtils.isNotEmpty(tfKeystore.getText()) && StringUtils.isNotEmpty(pfStorepass.getText())) { if (logger.isDebugEnabled()) { logger.debug("[LOAD ALIASES] there are values for the keytool command"); }//from w w w. j a va 2 s . com hboxAliasProgress.setVisible(true); cbAlias.valueProperty().unbindBidirectional(activeProfile.jarsignerConfigAliasProperty()); cbAlias.getItems().clear(); final String ks = tfKeystore.getText(); final String sp = pfStorepass.getText(); Task<Void> t = new Task<Void>() { public Void call() { try { updateMessage("Loading..."); updateProgress(0.1d, 1.0d); final List<String> aliases = keytoolCommand .findAliases(activeConfiguration.getKeytoolCommand().toString(), ks, sp); updateMessage("Updating..."); updateProgress(0.8d, 1.0d); Platform.runLater(() -> { if (CollectionUtils.isNotEmpty(aliases)) { cbAlias.getItems().addAll(aliases); cbAlias.valueProperty() .bindBidirectional(activeProfile.jarsignerConfigAliasProperty()); } cbAlias.setDisable(false); // might be an empty list for empty keystore cbAlias.requestFocus(); // leave the PasswordField hboxAliasProgress.setVisible(false); }); } catch (CommandExecutionException exc) { if (logger.isWarnEnabled()) { logger.warn("error getting aliases", exc); } Platform.runLater(() -> { cbAlias.setDisable(true); hboxAliasProgress.setVisible(false); }); } finally { updateMessage(""); updateProgress(0.0d, 1.0d); } return null; } }; lblAliasProgress.textProperty().bind(t.messageProperty()); pbAlias.progressProperty().bind(t.progressProperty()); new Thread(t).start(); } else { cbAlias.getItems().clear(); cbAlias.setDisable(true); } }
From source file:ui.main.MainViewController.java
@FXML public void handleTemporyButtonAction(ActionEvent event) { Task<Void> presenceWatchTask = new Task<Void>() { @Override//w w w . j a v a2 s . co m public Void call() throws Exception { while (true) { updateMessage(connectionManager.getMyPresence()); Thread.sleep(1000); } //return null; } }; presenceWatchTask.messageProperty() .addListener((obs, oldMessage, newMessage) -> presence.setText(newMessage)); new Thread(presenceWatchTask).start(); }
From source file:ui.main.MainViewController.java
private void showAccountInfo() { //this method shows the account name and presence //create a thread to check the user connected online or not Task<Void> presenceWatchTask = new Task<Void>() { @Override/*from w w w . j a v a 2 s. c o m*/ public Void call() throws Exception { while (true) { updateMessage(connectionManager.getMyPresence()); Thread.sleep(1000); } //return null; } }; presenceWatchTask.messageProperty() .addListener((obs, oldMessage, newMessage) -> presence.setText(newMessage)); new Thread(presenceWatchTask).start(); name.setText(connectionManager.getMyUsername()); try { if (connectionManager.getMyProfileAvatar() != null) { myAvatar.setImage(connectionManager.getMyProfileAvatar()); } else { myAvatar.setImage(defaultAvatar); } } catch (IOException e) { myAvatar.setImage(defaultAvatar); } catch (XMPPException e) { myAvatar.setImage(defaultAvatar); } catch (NullPointerException e) { myAvatar.setImage(defaultAvatar); } finally { myAvatar.setFitHeight(120); myAvatar.setFitWidth(100); } }
From source file:frontend.GUIController.java
public Thread processInput(Runnable rSuccess, Runnable rFail) throws Exception { System.out.println("Steping to next step..."); progressBar.progressProperty().unbind(); progressMessage.textProperty().unbind(); next1.setDisable(true);//w w w . jav a 2 s .c o m final ArrayList<String> comboBoxValues = new ArrayList<String>(); for (ComboBox<String> c : comboBoxes) { comboBoxValues.add(c.getValue()); } Task<Boolean> t = new Task<Boolean>() { @Override protected Boolean call() throws Exception { updateMessage("Doing Prediction"); updateProgress(3, 10); int status = at.processAfterLoadFile(comboBoxValues, predModel.getValue(), visualize.isSelected(), predicted.isSelected()); if (status > 0) { System.err.println("ProcessAfterLoadFile Error occured."); return false; } updateMessage("Finished Prediction"); if (visualize.isSelected()) { updateProgress(5, 10); at.showVisualization(); updateMessage("Finished Visualization"); updateProgress(8, 10); } updateProgress(10, 10); updateMessage("Done"); //webpage.getChildren().add(new Browser(url)); //at.addTweets(at.outputDir+"/visualization/Sentiment.tsv", personData); return true; }; @Override protected void succeeded() { super.succeeded(); updateMessage("Done!"); } @Override protected void cancelled() { super.cancelled(); updateMessage("Cancelled!"); } @Override protected void failed() { super.failed(); updateMessage("Failed!"); } @Override protected void done() { super.done(); updateMessage("Done!"); } }; progressBar.progressProperty().bind(t.progressProperty()); progressMessage.textProperty().bind(t.messageProperty()); t.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { if (t.getValue()) { Platform.runLater(rSuccess); } else { Platform.runLater(rFail); } } }); Thread mythread = new Thread(t); mythread.start(); return mythread; }
From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java
@FXML private void cmdUpdateSET(ActionEvent event) { Task taskUpdateSET = new Task<Void>() { @Override//from www. j a v a 2 s . co m public Void call() { try { EntityManager entityManager = Utils.getInstance().getEntityManagerFactory() .createEntityManager(); entityManager.getTransaction().begin(); String temp = ""; Integer count = 0; entityManager.createQuery("delete from TblContribuyentes t").executeUpdate(); for (Integer i = 0; i <= 9; i++) { URL url = new URL( "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc" + String.valueOf(i) + ".zip"); ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8); zipStream.getNextEntry(); Scanner sc = new Scanner(zipStream, "UTF-8"); while (sc.hasNextLine()) { String[] ruc = sc.nextLine().split("\\|"); temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2]; if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) { TblContribuyentes c = new TblContribuyentes(); c.setRucSinDv(ruc[0]); c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1])); c.setDv(ruc[2]); entityManager.persist(c); updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i) + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count) + " de aprox. 850.000."); count++; } else { updateMessage(temp); } } entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); } updateMessage("Lista de RUC actualizada..."); return null; } catch (Exception ex) { App.showException(this.getClass().getName(), ex.getMessage(), ex); } return null; } }; lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty()); new Thread(taskUpdateSET).start(); }
From source file:snpviewer.SnpViewer.java
public void displayFlankingSnpIDs(final String chrom, final double start, final double end) { final Task<List<String>> displayTask = new Task<List<String>>() { @Override/*from www. j a v a 2 s. com*/ protected List<String> call() { updateProgress(-1, -1); updateTitle("Finding flanking SNPs"); updateMessage("Searching for nearest SNP in all files..."); //work out coordinates based on chromosome and pane sizes /* read SnpFiles to find closest SNPs - use binary search * to find nearby SNP and refine to closest */ List<SnpFile.SnpLine> startAndEndSnps = searchCoordinate(chrom, (int) start, (int) end); if (startAndEndSnps == null) { //DISPLAY ERROR HERE? return null; } String coordResult = "chr" + chrom + ":" + nf.format(startAndEndSnps.get(0).getPosition()) + "-" + nf.format(startAndEndSnps.get(1).getPosition()); String idResult = startAndEndSnps.get(0).getId() + ";" + startAndEndSnps.get(1).getId(); List<String> result = new ArrayList(); result.add(coordResult); result.add(idResult); return result; } }; setProgressMode(true); progressBar.progressProperty().bind(displayTask.progressProperty()); progressMessage.textProperty().unbind(); progressMessage.textProperty().bind(displayTask.messageProperty()); progressTitle.textProperty().unbind(); progressTitle.textProperty().bind(displayTask.titleProperty()); displayTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { setProgressMode(false); progressBar.progressProperty().unbind(); progressBar.progressProperty().set(0); progressTitle.textProperty().unbind(); progressMessage.textProperty().unbind(); progressTitle.setText(""); progressMessage.setText(""); } }); displayTask.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { setProgressMode(false); progressBar.progressProperty().unbind(); progressBar.progressProperty().set(0); progressTitle.textProperty().unbind(); progressMessage.textProperty().unbind(); progressTitle.setText(""); progressMessage.setText(""); Dialogs.showErrorDialog(null, "Error displaying flanking SNPs\n", "Display error", "SNP Viewer", displayTask.getException()); } }); displayTask.setOnCancelled(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { progressMessage.setText("Display flanking SNPs cancelled"); setProgressMode(false); progressBar.progressProperty().unbind(); progressBar.progressProperty().set(0); progressTitle.textProperty().unbind(); progressMessage.textProperty().unbind(); progressTitle.setText(""); progressMessage.setText(""); Dialogs.showErrorDialog(null, "User cancelled display.", "Display error", "SNP Viewer", displayTask.getException()); } }); cancelButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { displayTask.cancel(); } }); new Thread(displayTask).start(); try { List<String> result = displayTask.get(); FXMLLoader loader = new FXMLLoader(getClass().getResource("RegionReporter.fxml")); Stage stage = new Stage(); Pane page = (Pane) loader.load(); Scene scene = new Scene(page); stage.setScene(scene); stage.setTitle("SNP Viewer Region Summary"); stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png"))); RegionReporterController regionReporter = loader.<RegionReporterController>getController(); if (result == null) { regionReporter.setCoordinates("Error!"); regionReporter.setIds("Error!"); } else { regionReporter.setCoordinates(result.get(0)); regionReporter.setIds(result.get(1)); } scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm()); stage.setResizable(false); stage.initModality(Modality.NONE); stage.show(); } catch (InterruptedException | ExecutionException | IOException ex) { Dialogs.showErrorDialog(null, "Can't display flanking SNP IDs" + " - exception caught!\n\nPlease report this error.", "Error!", "SNP Viewer", ex); } }